blob: e5f99ed44f8538b62d063e74ae2a35e2dc5df501 [file] [log] [blame]
arovir01b0717b52018-09-05 17:03:25 +01001//
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
arovir01b0717b52018-09-05 17:03:25 +01003// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01008#include "Utils.hpp"
9
arovir01b0717b52018-09-05 17:03:25 +010010#include <armnn/ArmNN.hpp>
Ferran Balaguerd30093c2019-07-09 17:04:47 +010011#include <armnn/ILayerSupport.hpp>
12#include <armnn/BackendHelper.hpp>
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +010013#include <armnn/utility/Assert.hpp>
Jan Eilers0b7a4192020-03-09 18:20:42 +000014#include <armnn/utility/IgnoreUnused.hpp>
Matthew Sloyan9b088d92020-09-14 15:12:55 +010015#include <armnn/utility/NumericCast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010016
Matteo Martincigh00d6ed12019-11-28 17:13:24 +000017#include <armnnUtils/DataLayoutIndexed.hpp>
Mike Kelly4a956582020-02-28 10:32:09 +000018#include <armnnUtils/Transpose.hpp>
arovir01b0717b52018-09-05 17:03:25 +010019
Mike Kelly46272802019-08-14 17:00:48 +010020#include "1.0/FullyConnected.hpp"
21
arovir01b0717b52018-09-05 17:03:25 +010022#include <ActivationFunctor.h>
23#include <CpuExecutor.h>
24#include <OperationsUtils.h>
25
James Ward4e22f602020-10-20 15:50:33 +010026#include <armnnUtils/FloatingPointComparison.hpp>
arovir01b0717b52018-09-05 17:03:25 +010027
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
Sadik Armagan188675f2021-02-12 17:16:42 +000042#ifdef ARMNN_ANDROID_S
43#include <nnapi/Types.h>
44#endif
45
46
arovir01b0717b52018-09-05 17:03:25 +010047struct ConversionData
48{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010049 ConversionData(const std::vector<armnn::BackendId>& backends)
50 : m_Backends(backends)
51 , m_Network(nullptr, nullptr)
Finn Williams291a16b2020-08-19 22:54:00 +010052 , m_DynamicInputsEncountered(false)
arovir01b0717b52018-09-05 17:03:25 +010053 {}
54
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010055 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010056 armnn::INetworkPtr m_Network;
57 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
58 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
Finn Williams291a16b2020-08-19 22:54:00 +010059 bool m_DynamicInputsEncountered;
arovir01b0717b52018-09-05 17:03:25 +010060};
61
62class LayerInputHandle
63{
64public:
65 LayerInputHandle();
66 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
67
68 bool IsValid() const;
69
70 void Connect(armnn::IInputSlot& inputSlot);
71
Finn Williamsa4983ce2020-07-23 12:55:12 +010072 void Disconnect(armnn::IInputSlot& inputSlot);
73
arovir01b0717b52018-09-05 17:03:25 +010074 const armnn::TensorInfo& GetTensorInfo() const;
75
76private:
77 armnn::IOutputSlot* m_OutputSlot;
78 bool m_Valid;
79 armnn::TensorInfo m_TensorInfo;
80};
81
82class ConstTensorPin
83{
84public:
85 // Creates an invalid tensor pin (can be used to signal errors)
86 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
87 ConstTensorPin(bool optional = false);
88
89 // @param tensorInfo TensorInfo associated with the tensor.
90 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
91 // the model being converted.
92 // @param numBytes Number of bytes for the tensor data.
93 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
94 const armnn::PermutationVector& mappings);
95
96 ConstTensorPin(const ConstTensorPin& other) = delete;
97 ConstTensorPin(ConstTensorPin&& other) = default;
98
99 bool IsValid() const;
100 bool IsOptional() const;
101
102 const armnn::ConstTensor& GetConstTensor() const;
103 const armnn::ConstTensor* GetConstTensorPtr() const;
104
105private:
106 armnn::ConstTensor m_ConstTensor;
107
108 // Owned memory for swizzled tensor data, only required if the tensor needed
109 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
110 // the pools associated with the model being converted.
111 std::vector<uint8_t> m_SwizzledTensorData;
112
113 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
114 bool m_Optional;
115};
116
117} // namespace armnn_driver
118
119///
120/// Utility functions
121///
122
123namespace
124{
125
126using namespace armnn_driver;
127using namespace android::nn;
128
129// Convenience function to log the reason for failing to convert a model.
130// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
131template<class... Args>
132static bool Fail(const char* formatStr, Args&&... args)
133{
134 ALOGD(formatStr, std::forward<Args>(args)...);
135 return false;
136}
137
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100138// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
139// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
140#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100141try \
142{ \
143 for (auto&& backendId : backends) \
144 { \
145 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
Francis Murtagh01824732021-01-28 14:26:27 +0000146 if (layerSupportObject.IsBackendRegistered()) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100147 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100148 std::string reasonIfUnsupported; \
149 supported = \
Francis Murtagh01824732021-01-28 14:26:27 +0000150 layerSupportObject.func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100151 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100152 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100153 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100154 } \
155 else \
156 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100157 if (reasonIfUnsupported.size() > 0) \
158 { \
159 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
160 } \
161 else \
162 { \
163 ALOGD("%s: not supported by armnn", funcName); \
164 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100165 } \
166 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100167 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100168 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100169 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100170 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100171 } \
172 if (!supported) \
173 { \
174 ALOGD("%s: not supported by any specified backend", funcName); \
175 } \
176} \
177catch (const armnn::InvalidArgumentException &e) \
178{ \
179 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
180}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100181
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000182template<typename HalOperand>
183armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100184{
185 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
186}
187
Matthew Bentham912b3622019-05-03 15:49:14 +0100188inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100189{
Matthew Bentham912b3622019-05-03 15:49:14 +0100190 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
191 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
192 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100193}
194
Kevin May42477c12020-03-26 13:34:14 +0000195#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100196
Keith Davis71006492020-01-06 17:44:16 +0000197// Support within the 1.2 driver for specific tensor data types
Mike Kellyb5fdf382019-06-11 16:35:25 +0100198inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
199{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000200 return type == V1_2::OperandType::BOOL ||
Sadik Armagan793a70c2020-03-19 13:54:04 +0000201 type == V1_2::OperandType::TENSOR_BOOL8 ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000202 type == V1_2::OperandType::TENSOR_FLOAT16 ||
203 type == V1_2::OperandType::TENSOR_FLOAT32 ||
204 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
Keith Davis71006492020-01-06 17:44:16 +0000205 type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000206 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
207 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100208 type == V1_2::OperandType::TENSOR_INT32;
209}
210
211#endif
212
Kevin May42477c12020-03-26 13:34:14 +0000213#ifdef ARMNN_ANDROID_NN_V1_3
214
215// Support within the 1.3 driver for specific tensor data types
216inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
217{
218 return type == V1_3::OperandType::BOOL ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100219 type == V1_3::OperandType::TENSOR_BOOL8 ||
Kevin May42477c12020-03-26 13:34:14 +0000220 type == V1_3::OperandType::TENSOR_FLOAT16 ||
221 type == V1_3::OperandType::TENSOR_FLOAT32 ||
222 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100223 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
Kevin May42477c12020-03-26 13:34:14 +0000224 type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
225 type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
226 type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
227 type == V1_3::OperandType::TENSOR_INT32;
228}
229
230#endif
231
Mike Kellyb5fdf382019-06-11 16:35:25 +0100232inline bool IsBool(V1_0::Operand)
233{
234 return false;
235}
236
Kevin May42477c12020-03-26 13:34:14 +0000237inline bool Is12OrLaterOperand(V1_0::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100238{
239 return false;
240}
241
Kevin May42477c12020-03-26 13:34:14 +0000242#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100243
244inline bool IsBool(V1_2::Operand operand)
245{
246 return operand.type == V1_2::OperandType::BOOL;
247}
248
Sadik Armagan61113162019-07-25 09:09:40 +0100249/// Checks if a operand is 1_2 Operand
Kevin May42477c12020-03-26 13:34:14 +0000250inline bool Is12OrLaterOperand(V1_2::Operand)
251{
252 return true;
253}
254
255#endif
256
257#ifdef ARMNN_ANDROID_NN_V1_3
258
259inline bool IsBool(V1_3::Operand operand)
260{
261 return operand.type == V1_3::OperandType::BOOL;
262}
263
264/// Checks if a operand is 1_2 Operand
265inline bool Is12OrLaterOperand(V1_3::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100266{
267 return true;
268}
269
Mike Kellyb5fdf382019-06-11 16:35:25 +0100270#endif
271
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100272template<typename LayerHandleType>
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000273armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
274 LayerHandleType& inputLayer,
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100275 armnn::TensorInfo reshapeInfo)
276{
277 armnn::ReshapeDescriptor reshapeDescriptor;
278 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
279
280 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100281 ARMNN_ASSERT(reshapeLayer != nullptr);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100282
283 // Attach the input layer to the reshape layer
284 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
285 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
286
287 return *reshapeLayer;
288}
289
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000290bool BroadcastTensor(LayerInputHandle& input0,
291 LayerInputHandle& input1,
292 armnn::IConnectableLayer* startLayer,
293 ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100294{
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100295 ARMNN_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100296
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100297 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
298 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
299
300 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
301 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
302
303 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100304 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100305 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
306 input0.Connect(startLayer->GetInputSlot(0));
307 input1.Connect(startLayer->GetInputSlot(1));
308
Sadik Armagan64b19b52019-08-19 09:49:58 +0100309 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100310 }
311
312 // Since the number of dimensions do not match then we need to add degenerate dimensions
313 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
314
315 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100316 unsigned int sizeDifference = std::abs(armnn::numeric_cast<int>(inputDimensions0) -
317 armnn::numeric_cast<int>(inputDimensions1));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100318
319 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
320 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
321 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
322
323 const armnn::TensorShape& smallShape = smallInfo.GetShape();
324 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
325 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
326 {
327 reshapedDimensions[i] = smallShape[i - sizeDifference];
328 }
329
330 armnn::TensorInfo reshapedInfo = smallInfo;
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100331 reshapedInfo.SetShape(armnn::TensorShape{ armnn::numeric_cast<unsigned int>(reshapedDimensions.size()),
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100332 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100333
334 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
335 armnn::ReshapeDescriptor reshapeDescriptor;
336
337 bool isSupported = false;
338 FORWARD_LAYER_SUPPORT_FUNC(__func__,
339 IsReshapeSupported,
340 data.m_Backends,
341 isSupported,
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +0000342 smallInfo,
Sadik Armagan64b19b52019-08-19 09:49:58 +0100343 reshapedInfo,
344 reshapeDescriptor);
345 if (!isSupported)
346 {
347 return false;
348 }
349
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100350 ARMNN_ASSERT(data.m_Network != nullptr);
Sadik Armagan64b19b52019-08-19 09:49:58 +0100351 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100352
353 if (input0IsSmaller)
354 {
355 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
356 //
357 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100358 // | |
359 // Reshape |
360 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100361 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100362
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100363 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
364 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100365 }
366 else
367 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100368 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
369 //
370 // Input0 Input1
371 // | |
372 // | Reshape
373 // \ /
374 // StartLayer
375
arovir01b0717b52018-09-05 17:03:25 +0100376 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100377 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100378 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100379
380 return true;
arovir01b0717b52018-09-05 17:03:25 +0100381}
382
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000383void CalcPadding(uint32_t input,
384 uint32_t kernel,
385 uint32_t stride,
386 uint32_t& outPadHead,
387 uint32_t& outPadTail,
arovir01b0717b52018-09-05 17:03:25 +0100388 android::nn::PaddingScheme scheme)
389{
390 int32_t padHead;
391 int32_t padTail;
392 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100393 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
394 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
arovir01b0717b52018-09-05 17:03:25 +0100395}
396
Kevin May42477c12020-03-26 13:34:14 +0000397#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly86b36d42019-07-12 16:39:33 +0100398
399void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
400 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
401{
402 int32_t padHead;
403 int32_t padTail;
404 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100405 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
406 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
Mike Kelly86b36d42019-07-12 16:39:33 +0100407}
408
Mike Kelly26123db2020-01-15 10:02:33 +0000409void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100410 int32_t& outPadTail, android::nn::PaddingScheme scheme)
411{
412 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
413}
414
Mike Kelly86b36d42019-07-12 16:39:33 +0100415#endif
416
Matthew Bentham912b3622019-05-03 15:49:14 +0100417Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100418{
419 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100420 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100421 shape.dimensions = operand.dimensions;
422 shape.scale = operand.scale;
423 shape.offset = operand.zeroPoint;
424 return shape;
425}
426
Kevin May42477c12020-03-26 13:34:14 +0000427#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly46272802019-08-14 17:00:48 +0100428
429Shape GetOperandShape(const V1_2::Operand& operand)
430{
431 Shape shape;
432 shape.type = OperandType(operand.type);
433 shape.dimensions = operand.dimensions;
434 shape.scale = operand.scale;
435 shape.offset = operand.zeroPoint;
436 return shape;
437}
438
439#endif
440
Kevin May42477c12020-03-26 13:34:14 +0000441#ifdef ARMNN_ANDROID_NN_V1_3
442
443Shape GetOperandShape(const V1_3::Operand& operand)
444{
445 Shape shape;
446 shape.type = OperandType(operand.type);
447 shape.dimensions = operand.dimensions;
448 shape.scale = operand.scale;
449 shape.offset = operand.zeroPoint;
450 return shape;
451}
452
453#endif
454
arovir01b0717b52018-09-05 17:03:25 +0100455// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
456// 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 +0100457// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
458// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100459void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000460 const armnn::TensorInfo& weightInfo,
461 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100462{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000463 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100464 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000465 // NOTE: Bias scale is always set to 0 for per-axis quantization and
466 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
467 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100468 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000469 return biasScale * inputInfo.GetQuantizationScale();
470 };
471
472 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
473 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
474
475 biasInfo.SetQuantizationScales(biasScales);
476 biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
477
478 ALOGV("Bias quantization params have been updated for per-axis quantization");
479 }
480 else
481 {
482 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
483 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
484 {
James Ward4e22f602020-10-20 15:50:33 +0100485 if (armnnUtils::within_percentage_tolerance(biasInfo.GetQuantizationScale(), expectedBiasScale, 1.0f))
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000486 {
487 ALOGW("Bias quantization scale has been modified to match input * weights");
488 biasInfo.SetQuantizationScale(expectedBiasScale);
489 }
arovir01b0717b52018-09-05 17:03:25 +0100490 }
491 }
492}
493
494// 4D Tensor Permutations
495const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
David Monahan7f492ac2020-10-16 10:36:29 +0100496const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
arovir01b0717b52018-09-05 17:03:25 +0100497const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
498
499// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000500const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
501const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100502
503template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000504armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
505 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100506{
507 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000508 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
arovir01b0717b52018-09-05 17:03:25 +0100509
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100510 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100511
512 // Connect input to swizzle layer
513 input.Connect(layer->GetInputSlot(0));
514
515 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000516 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100517 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
518
519 return *layer;
520}
521
arovir01b0717b52018-09-05 17:03:25 +0100522bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
523 const armnn::TensorShape & outputShape,
524 uint32_t concatDim)
525{
526 // Validate the output shape is correct given the input shapes (which have just been validated)
527 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
528 if (outputShape.GetNumDimensions() != numDimensions)
529 {
530 return Fail("%s: Output shape has wrong number of dimensions", __func__);
531 }
532
533 unsigned int outputSizeAlongConcatenatedDimension = 0;
534 for (unsigned int i = 0; i < inputShapes.size(); i++)
535 {
536 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
537 }
538
539 for (unsigned int i = 0; i < numDimensions; ++i)
540 {
541 if (i == concatDim)
542 {
543 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
544 {
545 return Fail(
546 "%s: Invalid output shape for dimension %d (%d != %d)",
547 __func__,
548 i,
549 outputShape[i],
550 outputSizeAlongConcatenatedDimension);
551 }
552 }
553 else
554 {
555 if (outputShape[i] != inputShapes[0][i])
556 {
557 return Fail("%s: Invalid output shape", __func__);
558 }
559 }
560 }
561
562 return true;
563}
564
565bool RequiresReshape(armnn::TensorShape & inputShape)
566{
567 return inputShape.GetNumDimensions() < 3;
568}
569
arovir01b0717b52018-09-05 17:03:25 +0100570void SwizzleInputs(armnn::INetwork& network,
571 std::vector<LayerInputHandle>& inputs,
572 std::vector<armnn::TensorShape>& inputShapes,
573 const armnn::PermutationVector& mapping)
574{
575 if (!mapping.IsEqual(IdentityPermutation4D))
576 {
577 size_t nInputs = inputs.size();
578 for (size_t i=0; i<nInputs; ++i)
579 {
580 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000581 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100582 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
583 auto& outputInfo = outputSlot.GetTensorInfo();
584 // replace inputs with the swizzled ones
585 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
586 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
587 }
588 }
589}
590
Teresa Charlin185f5882020-04-06 21:59:18 +0100591bool TransposeInputTensors(ConversionData& data,
592 std::vector<LayerInputHandle>& inputs,
593 std::vector<armnn::TensorShape>& inputShapes,
594 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000595{
David Monahan7f492ac2020-10-16 10:36:29 +0100596 // If we have a IdentityPermutation4D or IdentityPermutation3D then we are not permuting
597 if (!mapping.IsEqual(IdentityPermutation4D) && !mapping.IsEqual(IdentityPermutation3D))
Kevin Mayaed08ac2019-12-12 16:33:31 +0000598 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100599 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000600 size_t nInputs = inputs.size();
601 for (size_t i=0; i<nInputs; ++i)
602 {
603 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000604 armnn::TransposeDescriptor transposeDesc;
605 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100606 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000607
608 bool isSupported = false;
609 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000610 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000611 data.m_Backends,
612 isSupported,
613 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100614 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000615 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000616 if (!isSupported)
617 {
618 return false;
619 }
620
621 }
622 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
623 }
624 return true;
625}
626
627
narpra01f176d5a2018-11-18 20:17:48 +0000628bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
629 int32_t & concatDimension,
630 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100631{
narpra01f176d5a2018-11-18 20:17:48 +0000632 bool needPermute = false;
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100633 ARMNN_ASSERT(numberOfDimensions >= 3);
arovir01b0717b52018-09-05 17:03:25 +0100634
635 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000636 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
637 // or along dimension 0 or 2 for a 3-D tensor.
638 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100639 {
narpra01f176d5a2018-11-18 20:17:48 +0000640 concatDimension = 1;
641 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
642 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100643 }
narpra01f176d5a2018-11-18 20:17:48 +0000644 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100645 {
narpra01f176d5a2018-11-18 20:17:48 +0000646 concatDimension = 0;
647 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
648 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100649 }
David Monahan7f492ac2020-10-16 10:36:29 +0100650 // If the tensor is 3-D and the concat dimension is 2 then we don't need to permute but we do need to change the
651 // permutation identity to only have 3 dimensions
652 else if (numberOfDimensions == 3 && concatDimension == 2)
653 {
654 permutationPair = std::make_pair(IdentityPermutation3D, IdentityPermutation3D);
655 }
narpra01f176d5a2018-11-18 20:17:48 +0000656 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100657}
658
659} // anonymous namespace
660
661namespace armnn_driver
662{
663
664//// Creates an ArmNN activation layer and connects it to the given layer, if the
665//// passed in AndroidNN activation function requires so.
666//// @return The end layer of the sequence of layers built for the given AndroidNN
667//// activation function or nullptr if an error occurred (e.g. unsupported activation).
668//// Note that the end layer matches the input layer if no activation is required
669//// (the sequence of layers has length 1).
670armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
671 ActivationFn activation,
672 armnn::IConnectableLayer* prevLayer,
673 ConversionData& data);
674
675} // namespace armnn_driver
676
677///
678/// Utility templates
679///
680
681namespace armnn_driver
682{
683
684using namespace android::nn;
685
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100686template<typename HalPolicy,
687 typename HalOperand = typename HalPolicy::Operand,
688 typename HalOperation = typename HalPolicy::Operation,
689 typename HalModel = typename HalPolicy::Model>
690const HalOperand* GetInputOperand(const HalOperation& operation,
691 uint32_t inputIndex,
692 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100693 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100694{
695 if (inputIndex >= operation.inputs.size())
696 {
saoste01b8471482018-10-10 09:44:51 +0100697 if (failOnIndexOutOfBounds)
698 {
699 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
700 }
arovir01b0717b52018-09-05 17:03:25 +0100701 return nullptr;
702 }
703
Kevin May42477c12020-03-26 13:34:14 +0000704 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100705 ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
Kevin May42477c12020-03-26 13:34:14 +0000706 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100707}
708
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100709template<typename HalPolicy,
710 typename HalOperand = typename HalPolicy::Operand,
711 typename HalOperation = typename HalPolicy::Operation,
712 typename HalModel = typename HalPolicy::Model>
713const HalOperand* GetOutputOperand(const HalOperation& operation,
714 uint32_t outputIndex,
715 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100716{
717 if (outputIndex >= operation.outputs.size())
718 {
719 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
720 return nullptr;
721 }
722
723 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100724 ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
arovir01b0717b52018-09-05 17:03:25 +0100725
Kevin May42477c12020-03-26 13:34:14 +0000726 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100727}
728
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100729template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100730 typename HalOperand = typename HalPolicy::Operand,
731 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100732const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100733 const HalModel& model,
734 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000735 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100736{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100737 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100738
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100739 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100740 switch (operand.lifetime)
741 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100742 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100743 {
744 // Constant found in model.operandValues
745 valueStart = &model.operandValues[operand.location.offset];
746 break;
747 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100748 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100749 {
750 // Constant specified via a Memory object
751 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
752 break;
753 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100754 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000755 {
756 // An optional input tensor with no values is not an error so should not register as a fail
757 if (optional)
758 {
759 valueStart = nullptr;
760 break;
761 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100762 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000763 }
arovir01b0717b52018-09-05 17:03:25 +0100764 default:
765 {
766 // Unsupported/invalid (e.g. can't get value of an input to the model)
767 Fail("%s: unsupported/invalid operand lifetime: %s",
768 __func__, toString(operand.lifetime).c_str());
769 valueStart = nullptr;
770 }
771 }
772
773 return valueStart;
774}
775
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100776template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100777 typename HalOperation = typename HalPolicy::Operation,
778 typename HalModel = typename HalPolicy::Model,
779 typename HalOperandType = typename HalPolicy::OperandType>
780bool GetOperandType(const HalOperation& operation,
781 uint32_t inputIndex,
782 const HalModel& model,
783 HalOperandType& type)
784{
785 using HalOperand = typename HalPolicy::Operand;
786
787 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
788 if (!operand)
789 {
790 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
791 }
792
793 type = operand->type;
794 return true;
795}
796
797template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000798 typename HalOperand = typename HalPolicy::Operand>
799bool IsOperandConstant(const HalOperand& operand)
800{
801 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
802
803 HalOperandLifeTime lifetime = operand.lifetime;
804
805 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
806 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
807 lifetime == HalOperandLifeTime::NO_VALUE;
808}
809
810template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100811 typename HalOperand = typename HalPolicy::Operand,
812 typename HalModel = typename HalPolicy::Model>
813ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
814 const HalModel& model,
815 const ConversionData& data,
816 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
817 const armnn::TensorShape* overrideTensorShape = nullptr,
818 bool optional = false)
819{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100820 if (!IsOperandTypeSupportedForTensors(operand.type))
821 {
822 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
823 return ConstTensorPin();
824 }
825
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000826 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100827 {
828 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
829 return ConstTensorPin();
830 }
831
832 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
833 if (!valueStart)
834 {
835 if (optional)
836 {
837 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
838 return ConstTensorPin(true);
839 }
840 // mandatory tensor with no values
841 Fail("%s: failed to get operand address", __func__);
842 return ConstTensorPin();
843 }
844
845 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000846 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
847 if (tensorInfo.HasPerAxisQuantization())
848 {
849 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
850 }
851
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100852 if (overrideTensorShape != nullptr)
853 {
854 tensorInfo.SetShape(*overrideTensorShape);
855 }
856 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
857}
858
859template<typename HalPolicy,
860 typename HalOperation = typename HalPolicy::Operation,
861 typename HalModel = typename HalPolicy::Model>
862ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
863 uint32_t inputIndex,
864 const HalModel& model,
865 const ConversionData& data,
866 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
867 const armnn::TensorShape* overrideTensorShape = nullptr,
868 bool optional = false)
869{
870 using HalOperand = typename HalPolicy::Operand;
871
872 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
873 if (!operand)
874 {
875 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
876 return ConstTensorPin();
877 }
878 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
879 model,
880 data,
881 dimensionMappings,
882 overrideTensorShape,
883 optional);
884}
885
886template<typename HalPolicy,
887 typename OutputType,
888 typename HalOperandType = typename HalPolicy::OperandType,
889 typename HalOperation = typename HalPolicy::Operation,
890 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100891bool GetInputScalar(const HalOperation& operation,
892 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100893 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100894 OutputType& outValue,
895 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100896 const ConversionData& data,
897 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100898{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100899 using HalOperand = typename HalPolicy::Operand;
900
901 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100902 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100903 {
904 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
905 }
906
Sadik Armagan813f2302020-05-19 14:10:30 +0100907 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100908 {
909 return Fail("%s: unexpected operand type: %s (should be %s)",
910 __func__, toString(operand->type).c_str(), toString(type).c_str());
911 }
912
Sadik Armagan813f2302020-05-19 14:10:30 +0100913 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100914 {
915 return Fail("%s: incorrect operand location length: %i (should be %i)",
916 __func__, operand->location.length, sizeof(OutputType));
917 }
918
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100919 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100920 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100921 {
922 return Fail("%s: failed to get address for operand", __func__);
923 }
924
Sadik Armagan813f2302020-05-19 14:10:30 +0100925 if(!optional)
926 {
927 outValue = *(static_cast<const OutputType*>(valueAddress));
928 }
929
arovir01b0717b52018-09-05 17:03:25 +0100930 return true;
931}
932
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100933template<typename HalPolicy,
934 typename HalOperation = typename HalPolicy::Operation,
935 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100936bool GetInputInt32(const HalOperation& operation,
937 uint32_t inputIndex,
938 int32_t& outValue,
939 const HalModel& model,
940 const ConversionData& data)
941{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100942 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100943}
944
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100945template<typename HalPolicy,
946 typename HalOperation = typename HalPolicy::Operation,
947 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100948bool GetInputFloat32(const HalOperation& operation,
949 uint32_t inputIndex,
950 float& outValue,
951 const HalModel& model,
952 const ConversionData& data)
953{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100954 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100955}
956
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100957template<typename HalPolicy,
958 typename HalOperation = typename HalPolicy::Operation,
959 typename HalOperandType = typename HalPolicy::OperandType,
960 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100961bool GetInputActivationFunctionImpl(const HalOperation& operation,
962 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100963 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100964 ActivationFn& outActivationFunction,
965 const HalModel& model,
966 const ConversionData& data)
967{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100968 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100969 {
970 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
971 __func__,
972 toString(type).c_str(),
Sadik Armagan188675f2021-02-12 17:16:42 +0000973 toString(HalOperandType::INT32).c_str(),
974 toString(HalOperandType::TENSOR_INT32).c_str());
arovir01b0717b52018-09-05 17:03:25 +0100975 }
976
977 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100978 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100979 {
980 return Fail("%s: failed to get activation input value", __func__);
981 }
982 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
983 return true;
984}
985
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100986template<typename HalPolicy,
987 typename HalOperation = typename HalPolicy::Operation,
988 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100989bool GetInputActivationFunction(const HalOperation& operation,
990 uint32_t inputIndex,
991 ActivationFn& outActivationFunction,
992 const HalModel& model,
993 const ConversionData& data)
994{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100995 return GetInputActivationFunctionImpl<HalPolicy>(operation,
996 inputIndex,
997 HalPolicy::OperandType::INT32,
998 outActivationFunction,
999 model,
1000 data);
arovir01b0717b52018-09-05 17:03:25 +01001001}
1002
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001003template<typename HalPolicy,
1004 typename HalOperation = typename HalPolicy::Operation,
1005 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001006bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
1007 uint32_t inputIndex,
1008 ActivationFn& outActivationFunction,
1009 const HalModel& model,
1010 const ConversionData& data)
1011{
1012 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001013 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1014 inputIndex,
1015 HalPolicy::OperandType::INT32,
1016 outActivationFunction,
1017 model,
1018 data);
arovir01b0717b52018-09-05 17:03:25 +01001019}
1020
1021
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001022template<typename HalPolicy,
1023 typename HalOperation = typename HalPolicy::Operation,
1024 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001025bool GetOptionalInputActivation(const HalOperation& operation,
1026 uint32_t inputIndex,
1027 ActivationFn& activationFunction,
1028 const HalModel& model,
1029 const ConversionData& data)
1030{
1031 if (operation.inputs.size() <= inputIndex)
1032 {
1033 activationFunction = ActivationFn::kActivationNone;
1034 }
1035 else
1036 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001037 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001038 {
1039 return Fail("%s: Operation has invalid inputs", __func__);
1040 }
1041 }
1042 return true;
1043}
1044
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001045template<typename HalPolicy,
1046 typename ConvolutionDescriptor,
1047 typename HalOperation = typename HalPolicy::Operation,
1048 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001049bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1050 uint32_t dilationXIndex,
1051 ConvolutionDescriptor& descriptor,
1052 const HalModel& model,
1053 const ConversionData& data)
1054{
1055 bool success = true;
1056 if (operation.inputs.size() >= dilationXIndex + 2)
1057 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001058 success &= GetInputScalar<HalPolicy>(operation,
1059 dilationXIndex,
1060 HalPolicy::OperandType::INT32,
1061 descriptor.m_DilationX,
1062 model,
1063 data);
1064 success &= GetInputScalar<HalPolicy>(operation,
1065 dilationXIndex + 1,
1066 HalPolicy::OperandType::INT32,
1067 descriptor.m_DilationY,
1068 model,
1069 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001070 }
1071
1072 return success;
1073}
1074
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001075template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001076 typename HalOperation = typename HalPolicy::Operation,
1077 typename HalModel = typename HalPolicy::Model>
1078bool GetOptionalBool(const HalOperation& operation,
1079 uint32_t inputIndex,
1080 const HalModel& model,
1081 const ConversionData& data)
1082{
1083 using HalOperand = typename HalPolicy::Operand;
1084
1085 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1086 if (!operand)
1087 {
1088 return false;
1089 }
1090
1091 if (!IsBool(*operand))
1092 {
1093 return false;
1094 }
1095
1096 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1097 if (!valueAddress)
1098 {
1099 return false;
1100 }
1101
1102 if (*(static_cast<const bool*>(valueAddress)))
1103 {
1104 return true;
1105 }
1106 else
1107 {
1108 return false;
1109 }
1110}
1111
1112template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001113 typename HalOperand = typename HalPolicy::Operand,
1114 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001115bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001116 std::vector<int32_t>& outValues,
1117 const HalModel& model,
1118 const ConversionData& data)
1119{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001120 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001121 {
1122 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1123 }
1124
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001125 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001126 if (!startAddress)
1127 {
1128 return Fail("%s: failed to get operand address", __func__, operand.type);
1129 }
1130
1131 // Check number of bytes is sensible
1132 const uint32_t numBytes = operand.location.length;
1133 if (numBytes % sizeof(int32_t) != 0)
1134 {
1135 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1136 __func__, numBytes, sizeof(int32_t));
1137 }
1138
1139 outValues.resize(numBytes / sizeof(int32_t));
1140 memcpy(outValues.data(), startAddress, numBytes);
1141 return true;
1142}
1143
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001144template<typename HalPolicy,
1145 typename HalOperation = typename HalPolicy::Operation,
1146 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001147bool GetInputPaddingScheme(const HalOperation& operation,
1148 uint32_t inputIndex,
1149 PaddingScheme& outPaddingScheme,
1150 const HalModel& model,
1151 const ConversionData& data)
1152{
1153 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001154 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001155 {
1156 return Fail("%s: failed to get padding scheme input value", __func__);
1157 }
1158
1159 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1160 return true;
1161}
1162
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001163template<typename HalPolicy,
1164 typename HalOperation = typename HalPolicy::Operation,
1165 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001166LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1167 uint32_t inputIndex,
1168 const HalModel& model,
1169 ConversionData& data)
1170{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001171 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001172 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001173 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1174
1175 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001176 if (!operand)
1177 {
1178 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1179 return LayerInputHandle();
1180 }
1181
1182 if (!IsOperandTypeSupportedForTensors(operand->type))
1183 {
1184 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1185 return LayerInputHandle();
1186 }
1187
Sadik Armagan44bcc022019-06-18 17:21:36 +01001188 try
arovir01b0717b52018-09-05 17:03:25 +01001189 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001190 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001191 if (IsDynamicTensor(operandTensorInfo))
1192 {
1193 Fail("%s: dynamic input tensors are not supported", __func__);
1194 return LayerInputHandle();
1195 }
arovir01b0717b52018-09-05 17:03:25 +01001196
Sadik Armagan44bcc022019-06-18 17:21:36 +01001197 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001198 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001199 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001200 {
1201 // NOTE: We must check whether we can support the input tensor on at least one
1202 // of the provided backends; otherwise we cannot convert the operation
1203 bool isInputSupported = false;
1204 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1205 IsInputSupported,
1206 data.m_Backends,
1207 isInputSupported,
1208 operandTensorInfo);
1209
1210 if (!isInputSupported)
1211 {
1212 Fail("%s: unsupported input tensor", __func__);
1213 return LayerInputHandle();
1214 }
1215
James Ward4e22f602020-10-20 15:50:33 +01001216 [[clang::fallthrough]]; // intentional fallthrough
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001217 }
1218 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001219 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001220 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001221 // The tensor is either an operand internal to the model, or a model input.
1222 // It can be associated with an ArmNN output slot for an existing layer.
1223
1224 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1225 const uint32_t operandIndex = operation.inputs[inputIndex];
1226 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001227 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001228 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001229 case HalOperandLifeTime::CONSTANT_REFERENCE:
1230 {
1231 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1232 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1233 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001234 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001235 bool isSupported = false;
1236 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1237 IsConstantSupported,
1238 data.m_Backends,
1239 isSupported,
1240 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001241 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001242 {
1243 return LayerInputHandle();
1244 }
1245
1246 armnn::IConnectableLayer* constantLayer =
1247 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1248 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1249 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1250
1251 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1252 }
1253 else
1254 {
1255 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001256 return LayerInputHandle();
1257 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001258 break;
arovir01b0717b52018-09-05 17:03:25 +01001259 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001260 default:
arovir01b0717b52018-09-05 17:03:25 +01001261 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001262 // Unsupported lifetime for an input tensor
1263 Fail("%s: unsupported lifetime for input tensor: %s",
1264 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001265 return LayerInputHandle();
1266 }
arovir01b0717b52018-09-05 17:03:25 +01001267 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001268 }
1269 catch (UnsupportedOperand<HalOperandType>& e)
1270 {
1271 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1272 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001273 }
1274}
1275
Kevin May42477c12020-03-26 13:34:14 +00001276
1277#ifdef ARMNN_ANDROID_NN_V1_3
1278template<typename HalPolicy>
1279LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1280 uint32_t inputIndex,
1281 const::android::hardware::neuralnetworks::V1_3::Model& model,
1282 ConversionData& data)
1283{
1284 using HalOperand = typename HalPolicy::Operand;
1285 using HalOperandType = typename HalPolicy::OperandType;
1286 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1287
1288 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1289 if (!operand)
1290 {
1291 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1292 return LayerInputHandle();
1293 }
1294
1295 if (!IsOperandTypeSupportedForTensors(operand->type))
1296 {
1297 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1298 return LayerInputHandle();
1299 }
1300
1301 try
1302 {
1303 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Finn Williams9a044412020-08-17 19:08:35 +01001304
Kevin May42477c12020-03-26 13:34:14 +00001305 if (IsDynamicTensor(operandTensorInfo))
1306 {
Finn Williams291a16b2020-08-19 22:54:00 +01001307 data.m_DynamicInputsEncountered = true;
1308
Finn Williams9a044412020-08-17 19:08:35 +01001309 const uint32_t operandIndex = operation.inputs[inputIndex];
1310
1311 // Check if the dynamic input tensors have been inferred by one of the previous layers
1312 // If not we can't support them
Finn Williams291a16b2020-08-19 22:54:00 +01001313 if (data.m_OutputSlotForOperand.size() >= operandIndex && data.m_OutputSlotForOperand[operandIndex])
Finn Williams9a044412020-08-17 19:08:35 +01001314 {
1315 operandTensorInfo = data.m_OutputSlotForOperand[operandIndex]->GetTensorInfo();
1316 }
1317 else
1318 {
1319 Fail("%s: Type 2 dynamic input tensors are not supported", __func__);
1320 return LayerInputHandle();
1321 }
Kevin May42477c12020-03-26 13:34:14 +00001322 }
1323
1324 switch (operand->lifetime)
1325 {
1326 case HalOperandLifeTime::SUBGRAPH_INPUT:
1327 {
1328 // NOTE: We must check whether we can support the input tensor on at least one
1329 // of the provided backends; otherwise we cannot convert the operation
1330 bool isInputSupported = false;
1331 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1332 IsInputSupported,
1333 data.m_Backends,
1334 isInputSupported,
1335 operandTensorInfo);
1336
1337 if (!isInputSupported)
1338 {
1339 Fail("%s: unsupported input tensor", __func__);
1340 return LayerInputHandle();
1341 }
1342
James Ward4e22f602020-10-20 15:50:33 +01001343 [[clang::fallthrough]]; // intentional fallthrough
Kevin May42477c12020-03-26 13:34:14 +00001344 }
1345 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1346 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1347 {
1348 // The tensor is either an operand internal to the model, or a model input.
1349 // It can be associated with an ArmNN output slot for an existing layer.
1350
1351 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1352 const uint32_t operandIndex = operation.inputs[inputIndex];
1353 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1354 }
1355 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1356 case HalOperandLifeTime::CONSTANT_REFERENCE:
1357 {
1358 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1359 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1360 if (tensorPin.IsValid())
1361 {
1362 bool isSupported = false;
1363 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1364 IsConstantSupported,
1365 data.m_Backends,
1366 isSupported,
1367 tensorPin.GetConstTensor().GetInfo());
1368 if (!isSupported)
1369 {
1370 return LayerInputHandle();
1371 }
1372
1373 armnn::IConnectableLayer* constantLayer =
1374 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1375 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1376 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1377
1378 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1379 }
1380 else
1381 {
1382 Fail("%s: invalid operand tensor", __func__);
1383 return LayerInputHandle();
1384 }
1385 break;
1386 }
1387 default:
1388 {
1389 // Unsupported lifetime for an input tensor
1390 Fail("%s: unsupported lifetime for input tensor: %s",
1391 __func__, toString(operand->lifetime).c_str());
1392 return LayerInputHandle();
1393 }
1394 }
1395 }
1396 catch (UnsupportedOperand<HalOperandType>& e)
1397 {
1398 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1399 return LayerInputHandle();
1400 }
1401}
1402#endif
1403
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001404template<typename HalPolicy,
1405 typename HalOperation = typename HalPolicy::Operation,
1406 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001407bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1408 uint32_t operationOutputIndex,
1409 armnn::IConnectableLayer& layer,
1410 uint32_t layerOutputIndex,
1411 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001412 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001413 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001414 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001415 const ActivationFn& activationFunction = ActivationFn::kActivationNone,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001416 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001417{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001418 using HalOperand = typename HalPolicy::Operand;
1419
1420 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001421 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1422 {
1423 return false;
1424 }
1425
1426 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001427 if (overrideOutputInfo == nullptr)
1428 {
1429 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1430 }
1431 else
1432 {
1433 outputSlot.SetTensorInfo(*overrideOutputInfo);
1434 }
1435
Finn Williamsa4983ce2020-07-23 12:55:12 +01001436 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001437 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001438 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001439 // Type one dynamic tensors require the previous layer's output shape for inference
1440 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1441 {
1442 if(!layer.GetInputSlot(inputSlotIndex).GetConnection())
1443 {
1444 return false;
1445 }
1446 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001447 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001448 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001449 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001450 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1451
Sadik Armagandbda4b72020-09-03 11:33:07 +01001452 if(!isSupported)
1453 {
1454 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1455 {
1456 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1457 }
1458 return false;
1459 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001460 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001461
Finn Williamsa4983ce2020-07-23 12:55:12 +01001462 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
Kevin Mayfcf2a152020-09-08 16:06:32 +01001463
1464 if (activationFunction != ActivationFn::kActivationNone)
1465 {
1466 const armnn::TensorInfo& activationOutputInfo = outputSlot.GetTensorInfo();
1467 armnn::IConnectableLayer* const endLayer = ProcessActivation(activationOutputInfo, activationFunction,
1468 &layer, data);
1469
1470 if (!endLayer)
1471 {
1472 return Fail("%s: ProcessActivation failed", __func__);
1473 }
1474
1475 armnn::IOutputSlot& activationOutputSlot = endLayer->GetOutputSlot(layerOutputIndex);
1476 data.m_OutputSlotForOperand[operandIndex] = &activationOutputSlot;
1477 }
1478 else
1479 {
1480 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1481 }
Finn Williamsa4983ce2020-07-23 12:55:12 +01001482
Mike Kellyb5fdf382019-06-11 16:35:25 +01001483 return true;
1484}
1485
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001486template<typename HalPolicy,
1487 typename HalOperation = typename HalPolicy::Operation,
1488 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001489armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1490 uint32_t inputIndex,
1491 const HalModel& model,
1492 ConversionData& data)
1493{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001494 using HalOperand = typename HalPolicy::Operand;
1495
1496 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001497 if (!operand)
1498 {
1499 return armnn::DataLayout::NHWC;
1500 }
1501
1502 if (!IsBool(*operand))
1503 {
1504 return armnn::DataLayout::NHWC;
1505 }
1506
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001507 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001508 if (!valueAddress)
1509 {
1510 return armnn::DataLayout::NHWC;
1511 }
1512
1513 if (*(static_cast<const bool*>(valueAddress)))
1514 {
1515 return armnn::DataLayout::NCHW;
1516 }
1517 else
1518 {
1519 return armnn::DataLayout::NHWC;
1520 }
1521}
1522
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001523template<typename HalPolicy,
1524 typename HalOperation = typename HalPolicy::Operation,
1525 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001526bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1527 uint32_t outputIndex,
1528 armnn::IConnectableLayer& layer,
1529 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001530 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001531 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001532 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
1533 const ActivationFn& activationFunction = ActivationFn::kActivationNone)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001534{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001535 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1536 outputIndex,
1537 layer,
1538 outputIndex,
1539 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001540 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001541 overrideOutputInfo,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001542 validateFunc,
1543 activationFunction);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001544}
1545
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001546template<typename HalPolicy,
1547 typename HalOperation = typename HalPolicy::Operation,
1548 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001549bool ConvertToActivation(const HalOperation& operation,
1550 const char* operationName,
1551 const armnn::ActivationDescriptor& activationDesc,
1552 const HalModel& model,
1553 ConversionData& data)
1554{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001555 using HalOperand = typename HalPolicy::Operand;
1556
1557 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001558 if (!input.IsValid())
1559 {
1560 return Fail("%s: Input 0 is invalid", operationName);
1561 }
1562
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001563 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001564 if (!outputOperand)
1565 {
1566 return false;
1567 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001568
1569 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001570
1571 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001572
1573 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1574 {
1575 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1576 IsActivationSupported,
1577 data.m_Backends,
1578 isSupported,
1579 input.GetTensorInfo(),
1580 outInfo,
1581 activationDesc);
1582 };
1583
1584 if(IsDynamicTensor(outInfo))
1585 {
1586 isSupported = AreDynamicTensorsSupported();
1587 }
1588 else
1589 {
1590 validateFunc(outInfo, isSupported);
1591 }
1592
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001593 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001594 {
1595 return false;
1596 }
1597
1598 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001599 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001600 input.Connect(layer->GetInputSlot(0));
1601
Finn Williamsa4983ce2020-07-23 12:55:12 +01001602 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001603}
1604
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001605template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001606 typename HalOperation = typename HalPolicy::Operation,
1607 typename HalModel = typename HalPolicy::Model>
1608bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1609{
1610 armnn::ActivationDescriptor desc;
1611 desc.m_Function = armnn::ActivationFunction::ReLu;
1612
1613 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1614}
1615
1616template<typename HalPolicy,
1617 typename HalOperation = typename HalPolicy::Operation,
1618 typename HalModel = typename HalPolicy::Model>
1619bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1620{
1621 armnn::ActivationDescriptor desc;
1622 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1623 desc.m_A = 1.0f;
1624 desc.m_B = -1.0f;
1625
1626 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1627}
1628
1629template<typename HalPolicy,
1630 typename HalOperation = typename HalPolicy::Operation,
1631 typename HalModel = typename HalPolicy::Model>
1632bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1633{
1634 armnn::ActivationDescriptor desc;
1635 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1636 desc.m_A = 6.0f;
1637
1638 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1639}
1640
1641template<typename HalPolicy,
1642 typename HalOperation = typename HalPolicy::Operation,
1643 typename HalModel = typename HalPolicy::Model>
1644bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1645{
1646 armnn::ActivationDescriptor desc;
1647 desc.m_Function = armnn::ActivationFunction::TanH;
1648 desc.m_A = 1.0f; // android nn does not support tanH parameters
1649 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1650
1651 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1652}
1653
1654template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001655 typename HalOperation = typename HalPolicy::Operation,
1656 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001657bool ConvertPaddings(const HalOperation& operation,
1658 const HalModel& model,
1659 ConversionData& data,
1660 unsigned int rank,
1661 armnn::PadDescriptor& padDescriptor)
1662{
1663 using HalOperand = typename HalPolicy::Operand;
1664
1665 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1666 if (!paddingsOperand)
1667 {
1668 return Fail("%s: Could not read paddings operand", __func__);
1669 }
1670
1671 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1672 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1673 {
1674 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1675 }
1676
1677 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001678 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1679 {
1680 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1681 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001682
1683 // add padding for each dimension of input tensor.
1684 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1685 {
1686 int paddingBeforeInput = paddings[i];
1687 int paddingAfterInput = paddings[i + 1];
1688
1689 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1690 {
1691 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1692 }
1693
1694 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1695 }
1696
1697 return true;
1698}
1699
1700template<typename HalPolicy,
1701 typename HalOperation = typename HalPolicy::Operation,
1702 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001703bool ConvertPooling2d(const HalOperation& operation,
1704 const char* operationName,
1705 armnn::PoolingAlgorithm poolType,
1706 const HalModel& model,
1707 ConversionData& data)
1708{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001709 using HalOperand = typename HalPolicy::Operand;
1710 using HalOperandType = typename HalPolicy::OperandType;
1711
1712 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001713 if (!input.IsValid())
1714 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001715 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001716 }
1717
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001718 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001719 if (!output)
1720 {
1721 return Fail("%s: Could not read output 0", __func__);
1722 }
1723
1724 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1725 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1726
arovir01b0717b52018-09-05 17:03:25 +01001727 armnn::Pooling2dDescriptor desc;
1728 desc.m_PoolType = poolType;
1729 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001730 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001731
1732 ActivationFn activation;
1733
Sadik Armagan15d63e22019-07-26 16:59:35 +01001734 auto inputSize = operation.inputs.size();
1735
1736 if (inputSize >= 10)
1737 {
1738 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1739 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1740 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1741 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1742 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1743 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1744 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1745 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1746 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1747 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1748 {
1749 return Fail("%s: Operation has invalid inputs", operationName);
1750 }
1751
Kevin May42477c12020-03-26 13:34:14 +00001752 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001753 {
1754 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1755 }
1756 }
1757 else
arovir01b0717b52018-09-05 17:03:25 +01001758 {
1759 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1760 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001761 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1762 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1763 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1764 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1765 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1766 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001767 {
1768 return Fail("%s: Operation has invalid inputs", operationName);
1769 }
1770
Kevin May42477c12020-03-26 13:34:14 +00001771 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001772 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001773 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001774 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001775
1776 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1777 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1778 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1779
1780 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1781 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001782 }
1783
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001784 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001785
1786 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1787 {
1788 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1789 IsPooling2dSupported,
1790 data.m_Backends,
1791 isSupported,
1792 inputInfo,
1793 outputInfo,
1794 desc);
1795
1796 };
1797
1798 if(IsDynamicTensor(outputInfo))
1799 {
1800 isSupported = AreDynamicTensorsSupported();
1801 }
1802 else
1803 {
1804 validateFunc(outputInfo, isSupported);
1805 }
1806
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001807 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001808 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001809 return false;
arovir01b0717b52018-09-05 17:03:25 +01001810 }
arovir01b0717b52018-09-05 17:03:25 +01001811
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001812 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1813 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001814 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001815 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001816 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001817
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001818 input.Connect(pooling2dLayer->GetInputSlot(0));
1819
Finn Williamsa4983ce2020-07-23 12:55:12 +01001820 if (!isSupported)
1821 {
1822 return false;
1823 }
1824
Kevin Mayfcf2a152020-09-08 16:06:32 +01001825 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *pooling2dLayer, model,
1826 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001827}
1828
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001829template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001830 typename HalOperation = typename HalPolicy::Operation,
1831 typename HalModel = typename HalPolicy::Model>
1832bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001833{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001834 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001835
1836 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1837 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1838
1839 if (!input0.IsValid() || !input1.IsValid())
1840 {
1841 return Fail("%s: Operation has invalid inputs", __func__);
1842 }
1843
1844 // The FuseActivation parameter is always the input index 2
1845 // and it should be optional
1846 ActivationFn activationFunction;
1847 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1848 {
1849 return Fail("%s: Operation has invalid inputs", __func__);
1850 }
1851
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001852 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001853 if (!outputOperand)
1854 {
1855 return false;
1856 }
1857
1858 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1859 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1860
1861 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001862
1863 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001864 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1865 {
1866 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1867 IsAdditionSupported,
1868 data.m_Backends,
1869 isSupported,
1870 inputInfo0,
1871 inputInfo1,
1872 outputInfo);
1873 };
1874
1875 if(!IsDynamicTensor(outputInfo))
1876 {
1877 validateFunc(outputInfo, isSupported);
1878 }
1879 else
1880 {
1881 isSupported = AreDynamicTensorsSupported();
1882 }
1883
Mike Kelly46272802019-08-14 17:00:48 +01001884 if (!isSupported)
1885 {
1886 return false;
1887 }
1888
1889 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01001890
Kevin Mayfcf2a152020-09-08 16:06:32 +01001891 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1892 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01001893 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01001894 return false;
1895 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01001896
Kevin Mayfcf2a152020-09-08 16:06:32 +01001897 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
1898 data, nullptr, validateFunc, activationFunction);
1899
Mike Kelly46272802019-08-14 17:00:48 +01001900}
1901
1902template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001903 typename HalOperation = typename HalPolicy::Operation,
1904 typename HalModel = typename HalPolicy::Model>
1905bool ConvertArgMinMax(const HalOperation& operation,
1906 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001907 ConversionData& data,
1908 armnn::ArgMinMaxFunction argMinMaxFunction)
1909{
1910 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1911
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001912 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001913 using HalOperandType = typename HalPolicy::OperandType;
1914
1915 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1916
1917 if (!input0.IsValid())
1918 {
1919 return Fail("%s: Operation has invalid inputs", __func__);
1920 }
1921
1922 int32_t axis;
1923 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1924 {
1925 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1926 }
1927
1928 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1929 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1930
1931 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1932 {
1933 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1934 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1935 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1936 return Fail("%s: Axis must be in range [-n, n)", __func__);
1937 }
1938
1939 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1940 if (!output)
1941 {
1942 return Fail("%s: Could not read output 0", __func__);
1943 }
1944
1945 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1946
1947 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001948
1949 armnn::ArgMinMaxDescriptor descriptor;
1950 descriptor.m_Function = argMinMaxFunction;
1951 descriptor.m_Axis = axis;
1952
1953 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001954
1955 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1956 {
1957 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1958 IsArgMinMaxSupported,
1959 data.m_Backends,
1960 isSupported,
1961 inputInfo0,
1962 outputInfo,
1963 descriptor);
1964 };
1965
1966 if(IsDynamicTensor(outputInfo))
1967 {
1968 isSupported = AreDynamicTensorsSupported();
1969 }
1970 else
1971 {
1972 validateFunc(outputInfo, isSupported);
1973 }
1974
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001975 if (!isSupported)
1976 {
1977 return false;
1978 }
1979
1980 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1981 assert(layer != nullptr);
1982
1983 input0.Connect(layer->GetInputSlot(0));
1984
Finn Williamsa4983ce2020-07-23 12:55:12 +01001985 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001986}
1987
1988template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001989 typename HalOperation = typename HalPolicy::Operation,
1990 typename HalModel = typename HalPolicy::Model>
1991bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001992{
Keith Davis6e4081f2020-09-03 13:17:21 +01001993 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001994 using HalOperandType = typename HalPolicy::OperandType;
1995
1996 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1997 if (operation.inputs.size() <= 1)
1998 {
1999 return Fail("%s: Operation has insufficient arguments", __func__);
2000 }
2001
2002 // Get inputs and outputs
2003 const std::size_t numInputTensors = operation.inputs.size() - 1;
2004
2005 int32_t concatDim;
2006 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
2007 {
2008 return Fail("%s: Operation has invalid inputs", __func__);
2009 }
2010
2011 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2012 if (!outputOperand)
2013 {
2014 return Fail("%s: Operation has no outputs", __func__);
2015 }
2016
Keith Davis6e4081f2020-09-03 13:17:21 +01002017 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
2018 armnn::TensorShape outputShape = outputInfo.GetShape();
2019 const bool isDynamicTensor = IsDynamicTensor(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002020 //
2021 // handle negative concat dims along the lines of tensorflow as described here:
2022 // https://www.tensorflow.org/api_docs/python/tf/concat
2023 // "negative axis refers to axis + rank(values)-th dimension"
2024 //
2025 if (concatDim < 0)
2026 {
2027 concatDim += outputShape.GetNumDimensions();
2028 }
2029
2030 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2031 {
2032 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2033 }
2034
2035 std::vector<LayerInputHandle> inputHandles;
2036 std::vector<armnn::TensorShape> inputShapes;
2037
2038 inputHandles.reserve(numInputTensors);
2039 inputShapes.reserve(numInputTensors);
2040
Keith Davis6e4081f2020-09-03 13:17:21 +01002041 bool inputsHaveBeenReshaped = false;
2042 unsigned int tensorDimensionsAdded = 0;
Mike Kellyb8805202019-07-31 17:25:43 +01002043 for (uint32_t i = 0; i < numInputTensors; ++i)
2044 {
2045 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2046 if (!operand)
2047 {
2048 return Fail("%s: Operation has invalid inputs", __func__);
2049 }
2050
Teresa Charlin3b959602019-10-31 17:05:47 +00002051 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2052 if (!operandInputHandle.IsValid())
2053 {
2054 return Fail("%s: Operation has invalid inputs", __func__);
2055 }
Mike Kellyb8805202019-07-31 17:25:43 +01002056
Keith Davis6e4081f2020-09-03 13:17:21 +01002057 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002058 if (operandShape.GetNumDimensions() == 0)
2059 {
2060 return Fail("%s: Operands with rank 0 are not supported", __func__);
2061 }
2062
2063 if (RequiresReshape(operandShape))
2064 {
2065 inputsHaveBeenReshaped = true;
2066
2067 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2068
2069 // Expand the tensor to three dimensions
2070 if (operandShape.GetNumDimensions() == 2)
2071 {
2072 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2073 tensorDimensionsAdded = 1;
2074 }
2075 else
2076 {
2077 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2078 tensorDimensionsAdded = 2;
2079 }
2080
Kevin Mayaed08ac2019-12-12 16:33:31 +00002081 armnn::ReshapeDescriptor reshapeDescriptor;
2082 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2083
2084 bool isSupported = false;
2085 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2086 IsReshapeSupported,
2087 data.m_Backends,
2088 isSupported,
2089 operandInputHandle.GetTensorInfo(),
2090 reshapeInfo,
2091 reshapeDescriptor);
Keith Davis6e4081f2020-09-03 13:17:21 +01002092
Kevin Mayaed08ac2019-12-12 16:33:31 +00002093 if (!isSupported)
2094 {
2095 return false;
2096 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002097 armnn::IConnectableLayer& newReshape = AddReshapeLayer(*data.m_Network, operandInputHandle, reshapeInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002098
2099 // Point to the reshape operation rather then the input operation
Keith Davis6e4081f2020-09-03 13:17:21 +01002100 operandShape = reshapeInfo.GetShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002101 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2102 }
2103
2104 inputShapes.emplace_back(operandShape);
2105 inputHandles.emplace_back(operandInputHandle);
2106
2107 if (!inputHandles.back().IsValid())
2108 {
2109 return Fail("%s: Operation has invalid inputs", __func__);
2110 }
2111 }
2112
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002113 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002114
2115 if (inputsHaveBeenReshaped)
2116 {
2117 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2118 concatDim += tensorDimensionsAdded;
2119
2120 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2121 if (tensorDimensionsAdded == 1)
2122 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002123 if (IsDynamicTensor(outputInfo))
2124 {
2125 outputShape = armnn::TensorShape({1, 0, 0}, {true, false, false});
2126 }
2127 else
2128 {
2129 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2130 }
Mike Kellyb8805202019-07-31 17:25:43 +01002131 }
2132 else if (tensorDimensionsAdded == 2)
2133 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002134 if (IsDynamicTensor(outputInfo))
2135 {
2136 outputShape = armnn::TensorShape({1, 1, 0}, {true, true, false});
2137 }
2138 else
2139 {
2140 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2141 }
Mike Kellyb8805202019-07-31 17:25:43 +01002142 }
2143 }
2144
2145 // Check if permutations is required and get the pair of permutations required for the concatenation.
2146 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2147 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
Keith Davis6e4081f2020-09-03 13:17:21 +01002148 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
Keith Davis6e4081f2020-09-03 13:17:21 +01002149 bool needPermute = CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(),
2150 concatDim,
2151 permutationPair);
Mike Kellyb8805202019-07-31 17:25:43 +01002152
Keith Davis6e4081f2020-09-03 13:17:21 +01002153 // Only relevant to static tensors as dynamic output tensors will be transposed as a result of inferring from input
2154 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002155 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002156 if (needPermute)
2157 {
2158 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
2159 }
2160
2161 outputInfo.SetShape(outputShape);
Mike Kellyb8805202019-07-31 17:25:43 +01002162 }
Mike Kellyb8805202019-07-31 17:25:43 +01002163 // this is no-op for identity swizzles, otherwise it replaces both
2164 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002165 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002166 {
2167 return false;
2168 }
Mike Kellyb8805202019-07-31 17:25:43 +01002169
2170 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2171 armnn::OriginsDescriptor concatDescriptor;
2172
2173 try
2174 {
2175 // The concat descriptor is always created across the only supported concat dimension
2176 // which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
Keith Davis6e4081f2020-09-03 13:17:21 +01002177 concatDescriptor = armnn::CreateDescriptorForConcatenation(inputShapes.begin(),
2178 inputShapes.end(),
2179 concatDim);
2180 } catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002181 {
2182 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2183 }
2184
2185 // Validate the output shape is correct given the input shapes based on the
2186 // only valid concat dimension which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
Keith Davis6e4081f2020-09-03 13:17:21 +01002187 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002188 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002189 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2190 {
2191 return Fail("%s: Error validating the output shape for concat", __func__);
2192 }
Mike Kellyb8805202019-07-31 17:25:43 +01002193 }
2194
2195 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2196 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
Keith Davis6e4081f2020-09-03 13:17:21 +01002197 [](const LayerInputHandle& h)->const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
Mike Kellyb8805202019-07-31 17:25:43 +01002198
Keith Davis6e4081f2020-09-03 13:17:21 +01002199 bool isSupported = false;
2200 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported){
2201 FORWARD_LAYER_SUPPORT_FUNC(__func__, IsConcatSupported, data.m_Backends, isSupported, inputTensorInfos,
2202 outputInfo, concatDescriptor);
2203 };
2204
2205 if (!isDynamicTensor)
2206 {
2207 validateFunc(outputInfo, isSupported);
2208 }
2209 else
2210 {
2211 isSupported = AreDynamicTensorsSupported();
2212 }
2213
Mike Kellyb8805202019-07-31 17:25:43 +01002214 if (!isSupported)
2215 {
2216 return false;
2217 }
2218
2219 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2220 assert(layer != nullptr);
2221 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002222 // Connect inputs to the layer
2223 const int numInputSlots = layer->GetNumInputSlots();
2224 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2225 for (int i = 0; i < numInputSlots; ++i)
2226 {
2227 // connect the input directly to the merge (concat) layer
2228 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2229 }
2230
Keith Davis6e4081f2020-09-03 13:17:21 +01002231 // Transpose the output shape
2232 auto transposeOutputShape = [&](){
Mike Kelly4a956582020-02-28 10:32:09 +00002233 armnn::TransposeDescriptor transposeDesc;
2234 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002235 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2236 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2237 permutationPair.second);
Keith Davis6e4081f2020-09-03 13:17:21 +01002238 isSupported = false;
Kevin Mayaed08ac2019-12-12 16:33:31 +00002239 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002240 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002241 data.m_Backends,
2242 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002243 inputTransposeInfo,
2244 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002245 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002246 if (!isSupported)
2247 {
2248 return false;
2249 }
Mike Kellyb8805202019-07-31 17:25:43 +01002250 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Keith Davis6e4081f2020-09-03 13:17:21 +01002251 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network, layer->GetOutputSlot(0),
Mike Kelly4a956582020-02-28 10:32:09 +00002252 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002253 layer = &deswizzleLayer;
Keith Davis6e4081f2020-09-03 13:17:21 +01002254
2255 return true;
2256 };
2257
2258 if (needPermute && !isDynamicTensor)
2259 {
2260 transposeOutputShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002261 }
2262
2263 if (inputsHaveBeenReshaped)
2264 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002265 if (isDynamicTensor)
2266 {
2267 // Infer the output shapes of concat if outputs are type 1 dynamic
David Monahan7f492ac2020-10-16 10:36:29 +01002268 ARMNN_ASSERT(layer->GetOutputSlot(0).IsTensorInfoSet());
Keith Davis6e4081f2020-09-03 13:17:21 +01002269 if (!ValidateConcatOutputShape(inputShapes,
2270 layer->GetOutputSlot(0).GetTensorInfo().GetShape(),
2271 concatDim))
2272 {
2273 return Fail("%s: Error validating the output shape for concat", __func__);
2274 }
2275 transposeOutputShape();
2276 }
2277
Mike Kellyb8805202019-07-31 17:25:43 +01002278 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Mike Kellyb8805202019-07-31 17:25:43 +01002279 // Undo the reshape knowing the amount of dimensions added
2280 if (tensorDimensionsAdded == 1)
2281 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002282 afterConcatInfo.SetShape(
2283 armnn::TensorShape({afterConcatInfo.GetShape()[1], afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002284 }
2285 else if (tensorDimensionsAdded == 2)
2286 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002287 afterConcatInfo.SetShape(armnn::TensorShape({afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002288 }
2289
Kevin Mayaed08ac2019-12-12 16:33:31 +00002290 armnn::ReshapeDescriptor reshapeDescriptor;
2291 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
Keith Davis6e4081f2020-09-03 13:17:21 +01002292 armnn::TensorInfo concatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Kevin Mayaed08ac2019-12-12 16:33:31 +00002293
Keith Davis6e4081f2020-09-03 13:17:21 +01002294 isSupported = false;
2295 auto validateReshapeFunc = [&](const armnn::TensorInfo& afterConcatInfo, bool& isSupported){
2296 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2297 IsReshapeSupported,
2298 data.m_Backends,
2299 isSupported,
2300 concatInfo,
2301 afterConcatInfo,
2302 reshapeDescriptor);
2303 };
2304
2305 if (!IsDynamicTensor(afterConcatInfo))
2306 {
2307 validateReshapeFunc(afterConcatInfo, isSupported);
2308 }
2309 else
2310 {
2311 isSupported = AreDynamicTensorsSupported();
2312 }
2313
Kevin Mayaed08ac2019-12-12 16:33:31 +00002314 if (!isSupported)
2315 {
2316 return false;
2317 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002318 layer = &AddReshapeLayer(*data.m_Network, layer->GetOutputSlot(0), afterConcatInfo);
2319 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
2320 0,
2321 *layer,
2322 model,
2323 data,
2324 nullptr,
2325 validateReshapeFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002326 }
2327
Keith Davis6e4081f2020-09-03 13:17:21 +01002328 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002329}
2330
2331template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002332 typename HalOperation = typename HalPolicy::Operation,
2333 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002334bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2335{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002336 using HalOperand = typename HalPolicy::Operand;
2337 using HalOperandType = typename HalPolicy::OperandType;
2338
2339 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002340 if (!input.IsValid())
2341 {
2342 return Fail("%s: Operation has invalid inputs", __func__);
2343 }
2344
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002345 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002346 if (!output)
2347 {
2348 return Fail("%s: Could not read output 0", __func__);
2349 }
2350
2351 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002352 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002353
2354 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002355 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2356 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002357
2358 if (!weightsPin.IsValid() || !biasPin.IsValid())
2359 {
2360 return Fail("%s: Operation has invalid inputs", __func__);
2361 }
2362
2363 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002364 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002365 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2366
2367 armnn::Convolution2dDescriptor desc;
2368 desc.m_DataLayout = armnn::DataLayout::NHWC;
2369 ActivationFn activation;
2370
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002371 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002372 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002373 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2374 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2375 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2376 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2377 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2378 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002379 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002380 {
2381 return Fail("%s: Operation has invalid inputs", __func__);
2382 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002383 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002384 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002385 {
2386 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002387 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2388 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2389 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002390 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002391 {
2392 return Fail("%s: Operation has invalid inputs", __func__);
2393 }
2394
2395 const uint32_t kernelX = weights.GetShape()[2];
2396 const uint32_t kernelY = weights.GetShape()[1];
2397 const uint32_t inputX = inputInfo.GetShape()[2];
2398 const uint32_t inputY = inputInfo.GetShape()[1];
2399
2400 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2401 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002402 }
2403 else
2404 {
2405 return Fail("%s: Unsupported number of operation inputs", __func__);
2406 }
2407
2408 desc.m_BiasEnabled = true;
2409 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2410
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002411 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002412 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2413 {
2414 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2415 IsConvolution2dSupported,
2416 data.m_Backends,
2417 isSupported,
2418 inputInfo,
2419 outputInfo,
2420 desc,
2421 weights.GetInfo(),
2422 biases);
2423 };
2424
2425 if(!IsDynamicTensor(outputInfo))
2426 {
2427 validateFunc(outputInfo, isSupported);
2428 }
2429 else
2430 {
2431 isSupported = AreDynamicTensorsSupported();
2432 }
2433
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002434 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002435 {
2436 return false;
2437 }
2438
2439 armnn::IConnectableLayer* startLayer =
2440 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2441
2442 if (!startLayer)
2443 {
2444 return Fail("%s: AddConvolution2dLayer failed", __func__);
2445 }
2446
Mike Kellyb5fdf382019-06-11 16:35:25 +01002447 input.Connect(startLayer->GetInputSlot(0));
2448
Kevin Mayfcf2a152020-09-08 16:06:32 +01002449 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2450 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002451}
2452
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002453template<typename HalPolicy,
2454 typename HalOperation = typename HalPolicy::Operation,
2455 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002456bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2457{
2458 using HalOperand = typename HalPolicy::Operand;
2459 using HalOperandType = typename HalPolicy::OperandType;
2460
2461 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2462 if (!input.IsValid() )
2463 {
2464 return Fail("%s: Operation has invalid inputs", __func__);
2465 }
2466
2467 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2468 unsigned int rank = inputInfo.GetNumDimensions();
2469 if (rank != 4)
2470 {
2471 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2472 }
2473
2474 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2475 if (!output)
2476 {
2477 return Fail("%s: Could not read output 0", __func__);
2478 }
2479
2480 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002481
2482 armnn::DepthToSpaceDescriptor descriptor;
2483
2484 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2485 if (descriptor.m_BlockSize <= 1)
2486 {
2487 return Fail("%s: Block size must be at least 1 in all dimensions");
2488 }
2489
2490 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002491 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002492 {
2493 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2494 }
2495
2496 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002497 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2498 {
2499 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2500 IsDepthToSpaceSupported,
2501 data.m_Backends,
2502 isSupported,
2503 inputInfo,
2504 outputInfo,
2505 descriptor);
2506 };
2507
2508 if(!IsDynamicTensor(outputInfo))
2509 {
2510 validateFunc(outputInfo, isSupported);
2511 }
2512 else
2513 {
2514 isSupported = AreDynamicTensorsSupported();
2515 }
2516
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002517 if (!isSupported)
2518 {
2519 return false;
2520 }
2521
2522 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2523 assert(layer != nullptr);
2524 input.Connect(layer->GetInputSlot(0));
2525
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002526 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002527}
2528
2529template<typename HalPolicy,
2530 typename HalOperation = typename HalPolicy::Operation,
2531 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002532bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2533{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002534 using HalOperand = typename HalPolicy::Operand;
2535 using HalOperandType = typename HalPolicy::OperandType;
2536
2537 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002538
2539 if (!input.IsValid())
2540 {
2541 return Fail("%s: Operation has invalid inputs", __func__);
2542 }
2543
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002544 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002545
2546 if (!output)
2547 {
2548 return Fail("%s: Could not read output 0", __func__);
2549 }
2550
2551 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002552 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002553
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002554 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002555 // 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 +01002556 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002557
2558 if (weightsOperand == nullptr)
2559 {
2560 return Fail("%s: Operand is invalid", __func__);
2561 }
2562 armnn::DepthwiseConvolution2dDescriptor desc;
2563 desc.m_DataLayout = armnn::DataLayout::NHWC;
2564
Mike Kellyb5fdf382019-06-11 16:35:25 +01002565 // Reinterpret weight data as [ H, W, I, M ]
2566 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2567 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002568 inputInfo.GetShape()[3],
2569 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002570
2571 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2572 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2573
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002574 const ConstTensorPin weightsPin =
2575 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2576 1,
2577 model,
2578 data,
2579 HWIMToMIHW,
2580 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002581
2582 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002583 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002584
2585 if (!weightsPin.IsValid() || !biasPin.IsValid())
2586 {
2587 return Fail("%s: Operation has invalid inputs", __func__);
2588 }
2589
2590 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2591 armnn::ConstTensor bias = biasPin.GetConstTensor();
2592 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2593
2594 ActivationFn activation;
2595
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002596 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002597 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002598 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2599 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2600 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2601 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2602 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2603 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002604 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002605 {
2606 return Fail("%s: Operation has invalid inputs", __func__);
2607 }
2608 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002609 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002610 {
2611 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002612 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2613 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2614 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002615 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002616 {
2617 return Fail("%s: Operation has invalid inputs", __func__);
2618 }
2619
2620 const uint32_t kernelX = weights.GetShape()[3];
2621 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002622 const uint32_t inputX = inputInfo.GetShape()[2];
2623 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002624
2625 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2626 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2627 }
2628 else
2629 {
2630 return Fail("%s: Unsupported number of operation inputs", __func__);
2631 }
2632
2633 desc.m_BiasEnabled = true;
2634 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2635
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002636 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002637 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2638 {
2639 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2640 IsDepthwiseConvolutionSupported,
2641 data.m_Backends,
2642 isSupported,
2643 inputInfo,
2644 outputInfo,
2645 desc,
2646 weights.GetInfo(),
2647 biases);
2648 };
2649
2650 if(!IsDynamicTensor(outputInfo))
2651 {
2652 validateFunc(outputInfo, isSupported);
2653 }
2654 else
2655 {
2656 isSupported = AreDynamicTensorsSupported();
2657 }
2658
2659
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002660 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002661 {
2662 return false;
2663 }
2664
2665 armnn::IConnectableLayer* startLayer =
2666 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2667 if (!startLayer)
2668 {
2669 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2670 }
2671
Mike Kellyb5fdf382019-06-11 16:35:25 +01002672 input.Connect(startLayer->GetInputSlot(0));
2673
Kevin Mayfcf2a152020-09-08 16:06:32 +01002674 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2675 data, nullptr, validateFunc, activation);
arovir01b0717b52018-09-05 17:03:25 +01002676}
2677
Mike Kelly3c673942019-07-25 09:26:06 +01002678template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002679 typename HalOperation = typename HalPolicy::Operation,
2680 typename HalModel = typename HalPolicy::Model>
2681bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002682{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002683 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002684
2685 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2686 if (!input.IsValid())
2687 {
2688 return Fail("%s: Operation has invalid input", __func__);
2689 }
2690
Sadik Armagan98c0f662019-11-21 15:54:36 +00002691 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2692 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2693 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2694 {
2695 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2696 }
2697
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002698 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002699 if (!outputOperand)
2700 {
2701 return Fail("%s: Operation has invalid outputs", __func__);
2702 }
2703
2704 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002705
2706 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002707 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2708 {
2709 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2710 IsDequantizeSupported,
2711 data.m_Backends,
2712 isSupported,
2713 inputInfo,
2714 outputInfo);
2715 };
2716
2717 if(IsDynamicTensor(outputInfo))
2718 {
2719 isSupported = AreDynamicTensorsSupported();
2720 }
2721 else
2722 {
2723 validateFunc(outputInfo, isSupported);
2724 }
2725
Mike Kelly46272802019-08-14 17:00:48 +01002726 if (!isSupported)
2727 {
2728 return false;
2729 }
2730
2731 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2732 assert(layer != nullptr);
2733 input.Connect(layer->GetInputSlot(0));
2734
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002735 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002736}
2737
2738template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002739 typename HalOperation = typename HalPolicy::Operation,
2740 typename HalModel = typename HalPolicy::Model>
2741bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002742{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002743 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002744
2745 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2746 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2747
2748 if (!input0.IsValid() || !input1.IsValid())
2749 {
2750 return Fail("%s: Operation has invalid inputs", __func__);
2751 }
2752
2753 // The FuseActivation parameter is always the input index 2
2754 // and it should be optional
2755 ActivationFn activationFunction;
2756 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2757 {
2758 return Fail("%s: Operation has invalid inputs", __func__);
2759 }
2760
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002761 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002762 if (!output)
2763 {
2764 return Fail("%s: Could not read output 0", __func__);
2765 }
2766
2767 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002768
2769 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002770 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2771 {
2772 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2773 IsDivisionSupported,
2774 data.m_Backends,
2775 isSupported,
2776 input0.GetTensorInfo(),
2777 input1.GetTensorInfo(),
2778 outputInfo);
2779 };
2780
2781 if(!IsDynamicTensor(outputInfo))
2782 {
2783 validateFunc(outputInfo, isSupported);
2784 }
2785 else
2786 {
2787 isSupported = AreDynamicTensorsSupported();
2788 }
2789
Mike Kelly46272802019-08-14 17:00:48 +01002790 if (!isSupported)
2791 {
2792 return false;
2793 }
2794
2795 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01002796
Kevin Mayfcf2a152020-09-08 16:06:32 +01002797 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2798 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01002799 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01002800 return false;
Mike Kelly46272802019-08-14 17:00:48 +01002801 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01002802
2803 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2804 data, nullptr, validateFunc, activationFunction);
2805
Mike Kelly46272802019-08-14 17:00:48 +01002806}
2807
2808template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002809 typename HalOperation = typename HalPolicy::Operation,
2810 typename HalModel = typename HalPolicy::Model>
2811bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002812{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002813 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002814
2815 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2816 if (!input.IsValid())
2817 {
2818 return Fail("%s: Operation has invalid inputs", __func__);
2819 }
2820
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002821 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002822 if (!outputOperand)
2823 {
2824 return Fail("%s: Operation has invalid outputs", __func__);
2825 }
2826
2827 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002828
2829 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002830 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2831 {
2832 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2833 IsFloorSupported,
2834 data.m_Backends,
2835 isSupported,
2836 input.GetTensorInfo(),
2837 outputInfo);
2838 };
2839
2840 if(!IsDynamicTensor(outputInfo))
2841 {
2842 validateFunc(outputInfo, isSupported);
2843 }
2844 else
2845 {
2846 isSupported = AreDynamicTensorsSupported();
2847 }
2848
Mike Kelly46272802019-08-14 17:00:48 +01002849 if (!isSupported)
2850 {
2851 return false;
2852 }
2853
2854 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2855 assert(layer != nullptr);
2856 input.Connect(layer->GetInputSlot(0));
2857
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002858 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002859}
2860
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002861inline bool IsQSymm8(const V1_0::Operand&)
2862{
2863 return false;
2864}
2865
Kevin May42477c12020-03-26 13:34:14 +00002866#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002867
2868inline bool IsQSymm8(const V1_2::Operand& operand)
2869{
2870 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2871}
2872
2873#endif
2874
Kevin May42477c12020-03-26 13:34:14 +00002875#ifdef ARMNN_ANDROID_NN_V1_3
2876
2877inline bool IsQSymm8(const V1_3::Operand& operand)
2878{
2879 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2880}
2881
2882#endif
2883
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002884enum class DequantizeStatus
2885{
2886 SUCCESS,
2887 NOT_REQUIRED,
2888 INVALID_OPERAND
2889};
2890
2891using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2892
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002893template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002894 typename HalOperation = typename HalPolicy::Operation,
2895 typename HalModel = typename HalPolicy::Model>
2896DequantizeResult DequantizeIfRequired(size_t operand_index,
2897 const HalOperation& operation,
2898 const HalModel& model,
2899 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002900{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002901 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002902
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002903 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002904 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002905 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002906 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002907 }
2908
2909 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2910 {
2911 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002912 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002913 }
2914
2915 const size_t weightsInputIndex = operation.inputs[operand_index];
2916
2917 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2918 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002919 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002920 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002921 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002922 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002923 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2924 {
2925 continue;
2926 }
2927
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002928 size_t outOpIndex = weightsInputIndex + 1;
2929 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002930 {
2931 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002932 }
2933
2934 if (outOpIndex != weightsInputIndex)
2935 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002936 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002937 }
2938
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002939 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002940 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002941
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002942 if (!IsQSymm8(*operand))
2943 {
2944 // Only supporting dequantize from QSYMM8 to FLOAT
2945 break;
2946 }
2947
2948 // Allocate a new buffer for the dequantized data and manually dequantize
2949 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2950 if (!startValue)
2951 {
2952 // Failed to get the operand address
2953 break;
2954 }
2955
2956 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2957 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002958 const float quantizationScale = operand->scale;
2959
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002960 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2961 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2962 {
2963 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002964 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002965 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2966 }
2967
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002968 // Construct tensor info for dequantized ConstTensor
2969 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2970 operand->dimensions.data(),
2971 armnn::DataType::Float32);
2972
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002973 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2974 std::move(tensorInfo),
2975 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002976 }
2977
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002978 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002979}
2980
2981template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002982 typename HalOperation = typename HalPolicy::Operation,
2983 typename HalModel = typename HalPolicy::Model>
2984ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2985 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002986 const ConversionData& data,
2987 size_t operandIndex,
2988 bool optional = false)
2989{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002990 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2991
2992 DequantizeStatus status = std::get<3>(dequantized);
2993 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002994 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002995 case DequantizeStatus::INVALID_OPERAND:
2996 {
2997 // return invalid const tensor pin
2998 return ConstTensorPin();
2999 }
3000 case DequantizeStatus::NOT_REQUIRED:
3001 {
3002 return ConvertOperationInputToConstTensorPin<HalPolicy>(
3003 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
3004 }
3005 case DequantizeStatus::SUCCESS:
3006 default:
3007 {
3008 return ConstTensorPin(
3009 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
3010 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003011 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003012}
3013
3014
Mike Kelly46272802019-08-14 17:00:48 +01003015template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003016 typename HalOperation = typename HalPolicy::Operation,
3017 typename HalModel = typename HalPolicy::Model>
3018bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003019{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003020 using HalOperand = typename HalPolicy::Operand;
3021
Mike Kelly46272802019-08-14 17:00:48 +01003022 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3023 if (!input.IsValid())
3024 {
3025 return Fail("%s: Operation has invalid inputs", __func__);
3026 }
3027
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003028 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003029 if (!output)
3030 {
3031 return Fail("%s: Could not read output 0", __func__);
3032 }
3033
3034 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3035 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3036
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003037 LayerInputHandle weightsInput = LayerInputHandle();
3038 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3039 if (!weightsOperand)
Mike Kelly46272802019-08-14 17:00:48 +01003040 {
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003041 return Fail("%s: Could not read weights", __func__);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003042 }
3043
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003044 const armnn::TensorInfo& weightsInfo = GetTensorInfoForOperand(*weightsOperand);
3045 bool constantWeights = IsOperandConstant<HalPolicy>(*weightsOperand);
3046
3047 armnn::Optional<armnn::ConstTensor> optionalWeights = armnn::EmptyOptional();
3048 if (!constantWeights)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003049 {
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003050 weightsInput = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3051 if (!weightsInput.IsValid())
3052 {
3053 return Fail("%s: Operation has invalid inputs", __func__);
3054 }
3055 }
3056 else
3057 {
3058 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
3059 if (!weightsPin.IsValid())
3060 {
3061 return Fail("%s: Operation has invalid weights", __func__);
3062 }
3063 optionalWeights = armnn::Optional<armnn::ConstTensor>(weightsPin.GetConstTensor());
Mike Kelly46272802019-08-14 17:00:48 +01003064 }
3065
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003066 LayerInputHandle biasInput = LayerInputHandle();
3067 const HalOperand* biasOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3068 if (!biasOperand)
3069 {
3070 return Fail("%s: Could not read bias", __func__);
3071 }
3072 armnn::TensorInfo biasInfo = GetTensorInfoForOperand(*biasOperand);
3073 bool constantBias = IsOperandConstant<HalPolicy>(*biasOperand);
3074
3075 armnn::Optional<armnn::ConstTensor> optionalBias = armnn::EmptyOptional();
3076 if (!constantBias)
3077 {
3078 biasInput = ConvertToLayerInputHandle<HalPolicy>(operation, 2, model, data);
3079 if (!biasInput.IsValid())
3080 {
3081 return Fail("%s: Operation has invalid inputs", __func__);
3082 }
3083 }
3084 else
3085 {
3086 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
3087 if (!biasPin.IsValid())
3088 {
3089 return Fail("%s: Operation has invalid bias", __func__);
3090 }
3091 optionalBias = armnn::Optional<armnn::ConstTensor>(biasPin.GetConstTensor());
3092 }
3093
3094 if ((constantWeights && !constantBias) || (!constantWeights && constantBias))
3095 {
3096 return Fail("%s: Non-compatible weights and bias", __func__);
3097 }
3098
Mike Kelly46272802019-08-14 17:00:48 +01003099 armnn::TensorInfo reshapedInfo = inputInfo;
Mike Kelly46272802019-08-14 17:00:48 +01003100 try
3101 {
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003102 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weightsInfo.GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003103 }
3104 catch (const std::exception& e)
3105 {
Mike Kelly46272802019-08-14 17:00:48 +01003106 return Fail("%s: %s", __func__, e.what());
3107 }
3108
3109 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003110 SanitizeBiasQuantizationScale(biasInfo, weightsInfo, reshapedInfo);
Mike Kelly46272802019-08-14 17:00:48 +01003111
3112 ActivationFn activationFunction;
3113 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3114 {
3115 return Fail("%s: Operation has invalid inputs", __func__);
3116 }
3117
3118 armnn::FullyConnectedDescriptor desc;
3119 desc.m_TransposeWeightMatrix = true;
3120 desc.m_BiasEnabled = true;
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003121 desc.m_ConstantWeights = constantWeights;
Mike Kelly46272802019-08-14 17:00:48 +01003122
3123 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003124 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3125 {
Finn Williams49184462020-10-02 13:28:34 +01003126 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003127 weightsInfo.GetShape(),
Finn Williams49184462020-10-02 13:28:34 +01003128 outputInfo.GetShape(),
3129 desc.m_TransposeWeightMatrix))
3130 {
3131 isSupported = false;
3132 Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3133 return;
3134 }
3135
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003136 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003137 IsFullyConnectedSupported,
3138 data.m_Backends,
3139 isSupported,
3140 reshapedInfo,
3141 outputInfo,
3142 weightsInfo,
3143 biasInfo,
3144 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003145 };
3146
3147 if(!IsDynamicTensor(outputInfo))
3148 {
3149 validateFunc(outputInfo, isSupported);
3150 }
3151 else
3152 {
3153 isSupported = AreDynamicTensorsSupported();
3154 }
3155
Mike Kelly46272802019-08-14 17:00:48 +01003156 if (!isSupported)
3157 {
3158 return false;
3159 }
3160
3161 armnn::IConnectableLayer* startLayer =
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003162 data.m_Network->AddFullyConnectedLayer(desc,
3163 optionalWeights,
3164 optionalBias);
Mike Kelly46272802019-08-14 17:00:48 +01003165
Kevin Mayfcf2a152020-09-08 16:06:32 +01003166 if (inputInfo.GetNumDimensions() > 2U)
Mike Kelly46272802019-08-14 17:00:48 +01003167 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003168 armnn::ReshapeDescriptor reshapeDescriptor;
3169 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
Mike Kelly46272802019-08-14 17:00:48 +01003170
Kevin Mayfcf2a152020-09-08 16:06:32 +01003171 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3172 assert(reshapeLayer != nullptr);
3173 input.Connect(reshapeLayer->GetInputSlot(0));
3174 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3175 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003176 }
3177 else
3178 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003179 input.Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003180 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003181
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003182 // connect weights input
3183 if (!desc.m_ConstantWeights)
3184 {
3185 weightsInput.Connect(startLayer->GetInputSlot(1));
3186 biasInput.Connect(startLayer->GetInputSlot(2));
3187 }
3188
Kevin Mayfcf2a152020-09-08 16:06:32 +01003189 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3190 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003191}
3192
3193template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003194 typename HalOperation = typename HalPolicy::Operation,
3195 typename HalModel = typename HalPolicy::Model>
3196bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003197{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003198 using HalOperand = typename HalPolicy::Operand;
3199
Mike Kelly999e2092019-08-15 10:46:46 +01003200 if (operation.inputs.size() != 1)
3201 {
3202 return Fail("%s: Optional inputs are not supported", __func__);
3203 }
3204
Mike Kelly46272802019-08-14 17:00:48 +01003205 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3206 if (!input.IsValid())
3207 {
3208 return Fail("%s: Operation has invalid inputs", __func__);
3209 }
3210
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003211 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003212 if (!output)
3213 {
3214 return Fail("%s: Could not read output 0", __func__);
3215 }
3216
3217 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3218 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3219
Mike Kelly46272802019-08-14 17:00:48 +01003220 if (outputInfo.GetNumDimensions() != 4u)
3221 {
3222 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3223 }
3224
3225 armnn::L2NormalizationDescriptor desc;
3226 desc.m_DataLayout = armnn::DataLayout::NHWC;
3227
3228 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003229 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3230 {
3231 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3232 IsL2NormalizationSupported,
3233 data.m_Backends,
3234 isSupported,
3235 inputInfo,
3236 outputInfo,
3237 desc);
3238 };
3239
3240 if(!IsDynamicTensor(outputInfo))
3241 {
3242 validateFunc(outputInfo, isSupported);
3243 }
3244 else
3245 {
3246 isSupported = AreDynamicTensorsSupported();
3247 }
3248
Mike Kelly46272802019-08-14 17:00:48 +01003249 if (!isSupported)
3250 {
3251 return false;
3252 }
3253
3254 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3255 assert(layer != nullptr);
3256 input.Connect(layer->GetInputSlot(0));
3257
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003258 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003259}
3260
3261template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003262 typename HalOperation = typename HalPolicy::Operation,
3263 typename HalModel = typename HalPolicy::Model>
3264bool ConvertLocalResponseNormalization(const HalOperation& operation,
3265 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003266 ConversionData& data)
3267{
Mike Kelly999e2092019-08-15 10:46:46 +01003268 if (operation.inputs.size() != 5)
3269 {
3270 return Fail("%s: Optional inputs are not supported", __func__);
3271 }
3272
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003273 using HalOperand = typename HalPolicy::Operand;
3274 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003275
3276 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3277 if (!input.IsValid())
3278 {
3279 return Fail("%s: Operation has invalid inputs", __func__);
3280 }
3281
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003282 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003283 if (!output)
3284 {
3285 return Fail("%s: Could not read output 0", __func__);
3286 }
3287
3288 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3289 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3290
Mike Kelly46272802019-08-14 17:00:48 +01003291 if (outputInfo.GetNumDimensions() != 4u)
3292 {
3293 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3294 }
3295
3296 armnn::NormalizationDescriptor descriptor;
3297 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3298 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3299 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3300
3301 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003302 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003303 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3304 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3305 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3306 {
3307 return Fail("%s: Operation has invalid inputs", __func__);
3308 }
3309
3310 // ArmNN expects normSize to be the full size of the normalization
3311 // window rather than the radius as in AndroidNN.
3312 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3313
3314 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003315 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3316 {
3317 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3318 IsNormalizationSupported,
3319 data.m_Backends,
3320 isSupported,
3321 inputInfo,
3322 outputInfo,
3323 descriptor);
3324 };
3325
3326 if(!IsDynamicTensor(outputInfo))
3327 {
3328 validateFunc(outputInfo, isSupported);
3329 }
3330 else
3331 {
3332 isSupported = AreDynamicTensorsSupported();
3333 }
3334
Mike Kelly46272802019-08-14 17:00:48 +01003335 if (!isSupported)
3336 {
3337 return false;
3338 }
3339
3340
3341 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3342 assert(layer != nullptr);
3343 input.Connect(layer->GetInputSlot(0));
3344
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003345 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003346}
3347
3348template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003349 typename HalOperation = typename HalPolicy::Operation,
3350 typename HalModel = typename HalPolicy::Model>
3351bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003352{
Mike Kelly46272802019-08-14 17:00:48 +01003353 armnn::ActivationDescriptor desc;
3354 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3355
3356 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3357}
3358
3359template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003360 typename HalOperation = typename HalPolicy::Operation,
3361 typename HalModel = typename HalPolicy::Model>
3362bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003363{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003364 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003365
3366 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3367 if (!input.IsValid())
3368 {
3369 return Fail("%s: Operation has invalid inputs", __func__);
3370 }
3371
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003372 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003373 if (!output)
3374 {
3375 return Fail("%s: Could not read output 0", __func__);
3376 }
3377
3378 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003379
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003380 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003381 if (!axisOperand)
3382 {
3383 return Fail("%s: Could not read input 1", __func__);
3384 }
3385
3386 std::vector<int32_t> axis;
3387 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3388 {
3389 return Fail("%s: Input 1 has invalid values", __func__);
3390 }
3391
3392 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3393
3394 // Convert the axis to unsigned int and remove duplicates.
3395 unsigned int rank = inputInfo.GetNumDimensions();
3396 std::set<unsigned int> uniqueAxis;
3397 std::transform(axis.begin(), axis.end(),
3398 std::inserter(uniqueAxis, uniqueAxis.begin()),
3399 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3400
3401 // Get the "keep dims" flag.
3402 int32_t keepDims = 0;
3403 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3404 {
3405 return Fail("%s: Could not read input 2", __func__);
3406 }
3407
3408 armnn::MeanDescriptor descriptor;
3409 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3410 descriptor.m_KeepDims = keepDims > 0;
3411
3412 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003413 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3414 {
3415 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3416 IsMeanSupported,
3417 data.m_Backends,
3418 isSupported,
3419 inputInfo,
3420 outputInfo,
3421 descriptor);
3422 };
3423
3424 if(!IsDynamicTensor(outputInfo))
3425 {
3426 validateFunc(outputInfo, isSupported);
3427 }
3428 else
3429 {
3430 isSupported = AreDynamicTensorsSupported();
3431 }
3432
Mike Kelly46272802019-08-14 17:00:48 +01003433 if (!isSupported)
3434 {
3435 return false;
3436 }
3437
3438 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3439 assert(layer != nullptr);
3440 input.Connect(layer->GetInputSlot(0));
3441
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003442 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003443}
3444
3445template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003446 typename HalOperation = typename HalPolicy::Operation,
3447 typename HalModel = typename HalPolicy::Model>
3448bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003449{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003450 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003451
3452 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3453 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3454
3455 if (!input0.IsValid() || !input1.IsValid())
3456 {
3457 return Fail("%s: Operation has invalid inputs", __func__);
3458 }
3459
3460 // The FuseActivation parameter is always the input index 2
3461 // and it should be optional
3462 ActivationFn activationFunction;
3463 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3464 {
3465 return Fail("%s: Operation has invalid inputs", __func__);
3466 }
3467
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003468 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003469
3470 if (outputOperand == nullptr)
3471 {
3472 return false;
3473 }
3474
3475 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003476
3477 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003478 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3479 {
3480 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3481 IsMultiplicationSupported,
3482 data.m_Backends,
3483 isSupported,
3484 input0.GetTensorInfo(),
3485 input1.GetTensorInfo(),
3486 outputInfo);
3487 };
3488
3489 if(!IsDynamicTensor(outputInfo))
3490 {
3491 validateFunc(outputInfo, isSupported);
3492 }
3493 else
3494 {
3495 isSupported = AreDynamicTensorsSupported();
3496 }
3497
Mike Kelly46272802019-08-14 17:00:48 +01003498 if (!isSupported)
3499 {
3500 return false;
3501 }
3502
3503 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
Mike Kelly46272802019-08-14 17:00:48 +01003504
Kevin Mayfcf2a152020-09-08 16:06:32 +01003505 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3506 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01003507 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003508 return false;
3509 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01003510
Kevin Mayfcf2a152020-09-08 16:06:32 +01003511 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3512 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003513}
3514
3515template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003516 typename HalOperation = typename HalPolicy::Operation,
3517 typename HalModel = typename HalPolicy::Model>
3518bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003519{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003520 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003521
Mike Kelly3c673942019-07-25 09:26:06 +01003522 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3523 if (!input.IsValid())
3524 {
3525 return Fail("%s: Operation has invalid inputs", __func__);
3526 }
3527
3528 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3529 unsigned int rank = inputInfo.GetNumDimensions();
3530
3531 armnn::PadDescriptor descriptor;
3532 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3533 {
3534 return Fail("%s: Could not convert paddings", __func__);
3535 }
3536
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003537 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3538 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003539 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3540 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3541 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003542 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003543 {
3544 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3545 }
3546
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003547 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003548 if (!output)
3549 {
3550 return Fail("%s: Could not read output", __func__);
3551 }
3552
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003553 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003554
3555 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003556 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3557 {
3558 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3559 IsPadSupported,
3560 data.m_Backends,
3561 isSupported,
3562 inputInfo,
3563 outputInfo,
3564 descriptor);
3565 };
3566
3567 if(!IsDynamicTensor(outputInfo))
3568 {
3569 validateFunc(outputInfo, isSupported);
3570 }
3571 else
3572 {
3573 isSupported = AreDynamicTensorsSupported();
3574 }
3575
Mike Kelly3c673942019-07-25 09:26:06 +01003576 if (!isSupported)
3577 {
3578 return false;
3579 }
3580
3581 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3582 assert(layer != nullptr);
3583 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003584
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003585 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003586}
3587
Mike Kelly0a879362019-07-29 16:56:31 +01003588template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003589 typename HalOperation = typename HalPolicy::Operation,
3590 typename HalModel = typename HalPolicy::Model>
3591bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003592{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003593 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003594
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003595 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3596 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3597 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003598
3599 if (inputOperand == nullptr
3600 || requestedShapeOperand == nullptr
3601 || outputOperand == nullptr)
3602 {
3603 return Fail("%s: Operation has invalid inputs", __func__);
3604 }
3605
3606 if (requestedShapeOperand->dimensions.size() != 1)
3607 {
3608 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3609 __func__, requestedShapeOperand->dimensions.size());
3610 }
3611
3612 std::vector<int32_t> targetDimensions;
3613 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3614 {
3615 return Fail("%s: Could not read values of input 1", __func__);
3616 }
3617
3618 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3619
3620 Shape requestedShape;
3621 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3622 // function that resolves these values into a fully specified tensor shape.
3623 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3624 {
3625 return Fail("%s: Failed to resolve the requested shape", __func__);
3626 }
3627
Mike Kelly46272802019-08-14 17:00:48 +01003628 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3629 if (!input.IsValid())
3630 {
3631 return Fail("%s: Could not read input 0", __func__);
3632 }
3633
3634 armnn::ReshapeDescriptor reshapeDescriptor;
3635 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3636 requestedShape.dimensions.data());
3637
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003638 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3639
Mike Kelly46272802019-08-14 17:00:48 +01003640 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003641 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3642 {
3643 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3644 IsReshapeSupported,
3645 data.m_Backends,
3646 isSupported,
3647 input.GetTensorInfo(),
3648 outputInfo,
3649 reshapeDescriptor);
3650 };
3651
3652 if(!IsDynamicTensor(outputInfo))
3653 {
3654 validateFunc(outputInfo, isSupported);
3655 }
3656 else
3657 {
3658 isSupported = AreDynamicTensorsSupported();
3659 }
3660
Mike Kelly46272802019-08-14 17:00:48 +01003661 if (!isSupported)
3662 {
3663 return false;
3664 }
3665
3666 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3667 assert(layer != nullptr);
3668 input.Connect(layer->GetInputSlot(0));
3669
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003670 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003671}
3672
3673template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003674 typename HalOperation = typename HalPolicy::Operation,
3675 typename HalModel = typename HalPolicy::Model>
3676bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003677{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003678 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003679
Mike Kelly0a879362019-07-29 16:56:31 +01003680 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3681 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3682
3683 if (!input0.IsValid() || !input1.IsValid())
3684 {
3685 return Fail("%s: Operation has invalid inputs", __func__);
3686 }
3687
3688 // The FuseActivation parameter is always the input index 2
3689 // and it should be optional
3690 ActivationFn activationFunction;
3691 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3692 {
3693 return Fail("%s: Operation has invalid inputs", __func__);
3694 }
3695
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003696 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003697 if (!output)
3698 {
3699 return Fail("%s: Could not read output 0", __func__);
3700 }
3701
3702 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003703
3704 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003705 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3706 {
3707 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3708 IsSubtractionSupported,
3709 data.m_Backends,
3710 isSupported,
3711 input0.GetTensorInfo(),
3712 input1.GetTensorInfo(),
3713 outputInfo);
3714 };
3715
3716 if(IsDynamicTensor(outputInfo))
3717 {
3718 isSupported = AreDynamicTensorsSupported();
3719 }
3720 else
3721 {
3722 validateFunc(outputInfo, isSupported);
3723 }
3724
Mike Kelly0a879362019-07-29 16:56:31 +01003725 if (!isSupported)
3726 {
3727 return false;
3728 }
3729
3730 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
Mike Kelly0a879362019-07-29 16:56:31 +01003731
Kevin Mayfcf2a152020-09-08 16:06:32 +01003732 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3733 if (!isReshapeSupported)
Mike Kelly0a879362019-07-29 16:56:31 +01003734 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003735 return false;
Mike Kelly0a879362019-07-29 16:56:31 +01003736 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003737 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3738 data, nullptr, validateFunc, activationFunction);
Mike Kelly0a879362019-07-29 16:56:31 +01003739}
3740
Finn Williams23b87b32019-07-30 11:44:05 +01003741template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003742 typename HalOperation = typename HalPolicy::Operation,
3743 typename HalModel = typename HalPolicy::Model>
3744bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003745{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003746 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003747
3748 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3749 if (!input.IsValid())
3750 {
3751 return Fail("%s: Operation has invalid inputs", __func__);
3752 }
3753
3754 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3755 unsigned int rank = inputInfo.GetNumDimensions();
3756 if (rank > 4)
3757 {
3758 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3759 }
3760
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003761 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003762 if (!output)
3763 {
3764 return Fail("%s: Could not read output 0", __func__);
3765 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003766
3767 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003768 {
3769 return Fail("%s: Dynamic output tensors are not supported", __func__);
3770 }
3771
3772 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3773 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003774 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003775
3776 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3777
3778 std::vector<int32_t> axis;
3779 if (!axisOperand)
3780 {
3781 axis.assign(dimensionSequence,
3782 dimensionSequence + rank);
3783 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003784 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003785 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003786 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003787 }
3788
3789 std::vector<uint32_t> outputDims;
3790 for (unsigned int i = 0; i < rank; i++)
3791 {
3792 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3793 auto currentDimension = inputInfo.GetShape()[i];
3794 if (skipSqueeze || currentDimension != 1)
3795 {
3796 outputDims.push_back(currentDimension);
3797 }
3798 }
3799
3800 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3801
3802 armnn::TensorInfo outputInfo = inputInfo;
3803 outputInfo.SetShape(outShape);
3804
3805 armnn::ReshapeDescriptor reshapeDesc;
3806 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3807
3808 bool isSupported = false;
3809 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3810 IsReshapeSupported,
3811 data.m_Backends,
3812 isSupported,
3813 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003814 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003815 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003816
Mike Kelly46272802019-08-14 17:00:48 +01003817 if (!isSupported)
3818 {
3819 return false;
3820 }
3821
3822 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3823 assert(layer != nullptr);
3824 input.Connect(layer->GetInputSlot(0));
3825
3826 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3827}
3828
3829template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003830 typename HalOperation = typename HalPolicy::Operation,
3831 typename HalModel = typename HalPolicy::Model>
3832bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003833{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003834 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003835
3836 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3837 if (!input.IsValid())
3838 {
3839 return Fail("%s: Operation has invalid inputs", __func__);
3840 }
3841
3842 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3843 unsigned int rank = inputInfo.GetNumDimensions();
3844 if (rank > 4)
3845 {
3846 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3847 }
3848
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003849 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003850 if (!output)
3851 {
3852 return Fail("%s: Could not read output 0", __func__);
3853 }
3854
3855 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003856
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003857 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3858 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3859 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003860
3861 std::vector<int32_t> beginValues;
3862 std::vector<int32_t> endValues;
3863 std::vector<int32_t> stridesValues;
3864
3865 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003866 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003867 {
3868 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3869 {
3870 return false;
3871 }
3872
3873 if (operandValues.size() != rank)
3874 {
3875 return false;
3876 }
3877
3878 return true;
3879 };
3880
3881 if (!ValidateInputOperands(*beginOperand, beginValues)
3882 || !ValidateInputOperands(*endOperand, endValues)
3883 || !ValidateInputOperands(*stridesOperand, stridesValues))
3884 {
3885 return Fail("%s: Operation has invalid input operand", __func__);
3886 }
3887
3888 // Stride cannot have value '0'
3889 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3890 {
3891 return Fail("%s: Stride must be non-zero value.", __func__);
3892 }
3893
3894 armnn::StridedSliceDescriptor descriptor;
3895 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3896 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3897 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3898 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3899
3900 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3901 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3902 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3903 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3904 {
3905 return Fail("%s: Operation has invalid inputs", __func__);
3906 }
3907
3908 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003909 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3910 {
3911 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3912 IsStridedSliceSupported,
3913 data.m_Backends,
3914 isSupported,
3915 inputInfo,
3916 outputInfo,
3917 descriptor);
3918 };
3919
3920 if(IsDynamicTensor(outputInfo))
3921 {
3922 isSupported = AreDynamicTensorsSupported();
3923 }
3924 else
3925 {
3926 validateFunc(outputInfo, isSupported);
3927 }
3928
Mike Kelly46272802019-08-14 17:00:48 +01003929 if (!isSupported)
3930 {
3931 return false;
3932 }
3933
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003934 // Check if slice can fit in a inferred output
3935 armnn::TensorShape inputShape = inputInfo.GetShape();
3936 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3937 {
3938 int stride = descriptor.m_Stride[i];
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003939
3940 if (descriptor.m_ShrinkAxisMask & (1 << i))
3941 {
3942 // If the difference between the start point and the end point of the slice on an axis being shrunk
3943 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3944 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3945 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3946 {
3947 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3948 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003949
3950 if(stride < 0)
3951 {
3952 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3953 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003954 }
3955 }
3956
Mike Kelly46272802019-08-14 17:00:48 +01003957 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3958 assert(layer != nullptr);
3959 input.Connect(layer->GetInputSlot(0));
3960
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003961 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003962}
3963
3964template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003965 typename HalOperation = typename HalPolicy::Operation,
3966 typename HalModel = typename HalPolicy::Model>
3967bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003968{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003969 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003970 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003971
3972 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3973 if (!input.IsValid())
3974 {
3975 return Fail("%s: Operation has invalid inputs", __func__);
3976 }
3977
3978 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3979 unsigned int rank = inputInfo.GetNumDimensions();
3980 if (rank > 4)
3981 {
3982 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3983 }
3984
3985 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3986 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003987 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003988
3989 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003990 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003991 {
Mike Kelly46272802019-08-14 17:00:48 +01003992 for (unsigned int i = rank; i > 0; i--)
3993 {
Matthew Sloyan9b088d92020-09-14 15:12:55 +01003994 perm[rank - i] = armnn::numeric_cast<int> (i - 1);
Mike Kelly46272802019-08-14 17:00:48 +01003995 }
3996 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003997 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003998 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003999 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01004000 }
4001
4002 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
4003
Mike Kelly4a956582020-02-28 10:32:09 +00004004 armnn::TransposeDescriptor transposeDesc;
4005 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01004006
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00004007 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01004008 if (!output)
4009 {
4010 return Fail("%s: Could not read output 0", __func__);
4011 }
4012
4013 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
4014
4015 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004016 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4017 {
4018 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4019 IsTransposeSupported,
4020 data.m_Backends,
4021 isSupported,
4022 inputInfo,
4023 outputInfo,
4024 transposeDesc);
4025 };
4026
4027 if(IsDynamicTensor(outputInfo))
4028 {
4029 isSupported = AreDynamicTensorsSupported();
4030 }
4031 else
4032 {
4033 validateFunc(outputInfo, isSupported);
4034 }
4035
Mike Kelly46272802019-08-14 17:00:48 +01004036 if (!isSupported)
4037 {
4038 return false;
4039 }
4040
Mike Kelly4a956582020-02-28 10:32:09 +00004041 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01004042 assert(layer != nullptr);
4043 input.Connect(layer->GetInputSlot(0));
4044
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004045 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01004046}
4047
4048template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01004049 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01004050 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01004051 typename HalModel = typename HalPolicy::Model>
4052bool ConvertBatchToSpaceNd(const HalOperation& operation,
4053 const HalModel& model,
4054 ConversionData& data)
4055{
Finn Williams23b87b32019-07-30 11:44:05 +01004056
4057 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4058 if (!input.IsValid())
4059 {
4060 return Fail("%s: Operation has invalid inputs", __func__);
4061 }
4062
4063 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4064 if (!output)
4065 {
4066 return Fail("%s: Could not read output 0", __func__);
4067 }
4068
4069 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004070
4071 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4072 if (!blockOperand)
4073 {
4074 return Fail("%s: Could not read input 1", __func__);
4075 }
4076
4077 // Convert the block operand to int32
4078 std::vector<int32_t> block;
4079 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4080 {
4081 return Fail("%s: Input 1 has invalid values", __func__);
4082 }
4083
4084 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4085
4086 unsigned int rank = inputInfo.GetNumDimensions();
4087 if (rank != 4)
4088 {
4089 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4090 }
4091
4092 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4093 {
4094 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4095 " greater than or equal to 1", __func__);
4096 }
4097
4098 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4099 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4100 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4101
Kevin May42477c12020-03-26 13:34:14 +00004102 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004103 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004104 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004105 }
4106 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4107 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4108
4109 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004110 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4111 {
4112 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4113 IsBatchToSpaceNdSupported,
4114 data.m_Backends,
4115 isSupported,
4116 inputInfo,
4117 outputInfo,
4118 batchToSpaceNdDesc);
4119 };
4120
4121 if(!IsDynamicTensor(outputInfo))
4122 {
4123 validateFunc(outputInfo, isSupported);
4124 }
4125 else
4126 {
4127 isSupported = AreDynamicTensorsSupported();
4128 }
4129
4130
Finn Williams23b87b32019-07-30 11:44:05 +01004131 if (!isSupported)
4132 {
4133 return false;
4134 }
4135
4136 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4137 assert(layer != nullptr);
4138 input.Connect(layer->GetInputSlot(0));
4139
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004140 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004141}
Mike Kelly0a879362019-07-29 16:56:31 +01004142
Finn Williamsd74c5052019-07-30 17:06:00 +01004143template<typename HalPolicy,
4144 typename HalOperation = typename HalPolicy::Operation,
4145 typename HalOperand = typename HalPolicy::Operand,
4146 typename HalModel = typename HalPolicy::Model>
4147bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4148{
4149 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4150 if (!input.IsValid())
4151 {
4152 return Fail("%s: Operation has invalid inputs", __func__);
4153 }
4154
4155 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4156 unsigned int rank = inputInfo.GetNumDimensions();
4157 unsigned int spatialDim = rank - 2;
4158
4159 if (rank != 4)
4160 {
4161 Fail("%s: Only inputs with rank 4 are supported", __func__);
4162 }
4163
4164 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4165 if (!output)
4166 {
4167 return Fail("%s: Could not read output 0", __func__);
4168 }
4169
4170 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004171
4172 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4173 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4174
4175 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4176 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4177 {
4178 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4179 }
4180
4181 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004182 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4183 {
4184 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4185 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004186 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4187 {
4188 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4189 }
4190
4191 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4192 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4193 {
4194 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4195 }
4196
4197 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4198 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004199 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4200 {
4201 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4202 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004203 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4204 {
4205 int paddingBeforeInput = paddings[i];
4206 int paddingAfterInput = paddings[i + 1];
4207 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4208 {
4209 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4210 }
4211
4212 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4213 }
4214
4215 armnn::SpaceToBatchNdDescriptor descriptor;
4216 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4217 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4218 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4219
Kevin May42477c12020-03-26 13:34:14 +00004220 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004221 {
4222 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4223 }
4224
4225 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004226 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4227 {
4228 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4229 IsSpaceToBatchNdSupported,
4230 data.m_Backends,
4231 isSupported,
4232 inputInfo,
4233 outputInfo,
4234 descriptor);
4235 };
4236
4237 if(IsDynamicTensor(outputInfo))
4238 {
4239 isSupported = AreDynamicTensorsSupported();
4240 }
4241 else
4242 {
4243 validateFunc(outputInfo, isSupported);
4244 }
4245
Finn Williamsd74c5052019-07-30 17:06:00 +01004246 if (!isSupported)
4247 {
4248 return false;
4249 }
4250
4251 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4252 assert(layer != nullptr);
4253 input.Connect(layer->GetInputSlot(0));
4254
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004255 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004256}
4257
saoste01b8471482018-10-10 09:44:51 +01004258} // namespace armnn_driver