blob: 3432d9f89c8269564759039d83f9f42c37e403ab [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
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003037 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
3038 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003039
3040 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01003041 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003042 return Fail("%s: Operation has invalid weights", __func__);
3043 }
3044
3045 if (!biasPin.IsValid())
3046 {
3047 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003048 }
3049
3050 armnn::ConstTensor weights = weightsPin.GetConstTensor();
3051 armnn::ConstTensor bias = biasPin.GetConstTensor();
3052 armnn::TensorInfo reshapedInfo = inputInfo;
3053
3054 try
3055 {
3056 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003057 }
3058 catch (const std::exception& e)
3059 {
Mike Kelly46272802019-08-14 17:00:48 +01003060 return Fail("%s: %s", __func__, e.what());
3061 }
3062
3063 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
3064 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
3065
3066 ActivationFn activationFunction;
3067 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3068 {
3069 return Fail("%s: Operation has invalid inputs", __func__);
3070 }
3071
3072 armnn::FullyConnectedDescriptor desc;
3073 desc.m_TransposeWeightMatrix = true;
3074 desc.m_BiasEnabled = true;
3075
3076 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003077 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3078 {
Finn Williams49184462020-10-02 13:28:34 +01003079 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
3080 weights.GetInfo().GetShape(),
3081 outputInfo.GetShape(),
3082 desc.m_TransposeWeightMatrix))
3083 {
3084 isSupported = false;
3085 Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3086 return;
3087 }
3088
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003089 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly46272802019-08-14 17:00:48 +01003090 IsFullyConnectedSupported,
3091 data.m_Backends,
3092 isSupported,
3093 reshapedInfo,
3094 outputInfo,
3095 weights.GetInfo(),
3096 bias.GetInfo(),
3097 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003098 };
3099
3100 if(!IsDynamicTensor(outputInfo))
3101 {
3102 validateFunc(outputInfo, isSupported);
3103 }
3104 else
3105 {
3106 isSupported = AreDynamicTensorsSupported();
3107 }
3108
Mike Kelly46272802019-08-14 17:00:48 +01003109 if (!isSupported)
3110 {
3111 return false;
3112 }
3113
3114 armnn::IConnectableLayer* startLayer =
3115 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
Mike Kelly46272802019-08-14 17:00:48 +01003116
Kevin Mayfcf2a152020-09-08 16:06:32 +01003117 if (inputInfo.GetNumDimensions() > 2U)
Mike Kelly46272802019-08-14 17:00:48 +01003118 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003119 armnn::ReshapeDescriptor reshapeDescriptor;
3120 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
Mike Kelly46272802019-08-14 17:00:48 +01003121
Kevin Mayfcf2a152020-09-08 16:06:32 +01003122 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3123 assert(reshapeLayer != nullptr);
3124 input.Connect(reshapeLayer->GetInputSlot(0));
3125 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3126 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003127 }
3128 else
3129 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003130 input.Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003131 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003132
3133 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3134 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003135}
3136
3137template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003138 typename HalOperation = typename HalPolicy::Operation,
3139 typename HalModel = typename HalPolicy::Model>
3140bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003141{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003142 using HalOperand = typename HalPolicy::Operand;
3143
Mike Kelly999e2092019-08-15 10:46:46 +01003144 if (operation.inputs.size() != 1)
3145 {
3146 return Fail("%s: Optional inputs are not supported", __func__);
3147 }
3148
Mike Kelly46272802019-08-14 17:00:48 +01003149 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3150 if (!input.IsValid())
3151 {
3152 return Fail("%s: Operation has invalid inputs", __func__);
3153 }
3154
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003155 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003156 if (!output)
3157 {
3158 return Fail("%s: Could not read output 0", __func__);
3159 }
3160
3161 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3162 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3163
Mike Kelly46272802019-08-14 17:00:48 +01003164 if (outputInfo.GetNumDimensions() != 4u)
3165 {
3166 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3167 }
3168
3169 armnn::L2NormalizationDescriptor desc;
3170 desc.m_DataLayout = armnn::DataLayout::NHWC;
3171
3172 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003173 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3174 {
3175 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3176 IsL2NormalizationSupported,
3177 data.m_Backends,
3178 isSupported,
3179 inputInfo,
3180 outputInfo,
3181 desc);
3182 };
3183
3184 if(!IsDynamicTensor(outputInfo))
3185 {
3186 validateFunc(outputInfo, isSupported);
3187 }
3188 else
3189 {
3190 isSupported = AreDynamicTensorsSupported();
3191 }
3192
Mike Kelly46272802019-08-14 17:00:48 +01003193 if (!isSupported)
3194 {
3195 return false;
3196 }
3197
3198 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3199 assert(layer != nullptr);
3200 input.Connect(layer->GetInputSlot(0));
3201
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003202 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003203}
3204
3205template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003206 typename HalOperation = typename HalPolicy::Operation,
3207 typename HalModel = typename HalPolicy::Model>
3208bool ConvertLocalResponseNormalization(const HalOperation& operation,
3209 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003210 ConversionData& data)
3211{
Mike Kelly999e2092019-08-15 10:46:46 +01003212 if (operation.inputs.size() != 5)
3213 {
3214 return Fail("%s: Optional inputs are not supported", __func__);
3215 }
3216
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003217 using HalOperand = typename HalPolicy::Operand;
3218 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003219
3220 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3221 if (!input.IsValid())
3222 {
3223 return Fail("%s: Operation has invalid inputs", __func__);
3224 }
3225
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003226 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003227 if (!output)
3228 {
3229 return Fail("%s: Could not read output 0", __func__);
3230 }
3231
3232 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3233 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3234
Mike Kelly46272802019-08-14 17:00:48 +01003235 if (outputInfo.GetNumDimensions() != 4u)
3236 {
3237 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3238 }
3239
3240 armnn::NormalizationDescriptor descriptor;
3241 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3242 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3243 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3244
3245 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003246 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003247 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3248 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3249 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3250 {
3251 return Fail("%s: Operation has invalid inputs", __func__);
3252 }
3253
3254 // ArmNN expects normSize to be the full size of the normalization
3255 // window rather than the radius as in AndroidNN.
3256 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3257
3258 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003259 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3260 {
3261 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3262 IsNormalizationSupported,
3263 data.m_Backends,
3264 isSupported,
3265 inputInfo,
3266 outputInfo,
3267 descriptor);
3268 };
3269
3270 if(!IsDynamicTensor(outputInfo))
3271 {
3272 validateFunc(outputInfo, isSupported);
3273 }
3274 else
3275 {
3276 isSupported = AreDynamicTensorsSupported();
3277 }
3278
Mike Kelly46272802019-08-14 17:00:48 +01003279 if (!isSupported)
3280 {
3281 return false;
3282 }
3283
3284
3285 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3286 assert(layer != nullptr);
3287 input.Connect(layer->GetInputSlot(0));
3288
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003289 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003290}
3291
3292template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003293 typename HalOperation = typename HalPolicy::Operation,
3294 typename HalModel = typename HalPolicy::Model>
3295bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003296{
Mike Kelly46272802019-08-14 17:00:48 +01003297 armnn::ActivationDescriptor desc;
3298 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3299
3300 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3301}
3302
3303template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003304 typename HalOperation = typename HalPolicy::Operation,
3305 typename HalModel = typename HalPolicy::Model>
3306bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003307{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003308 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003309
3310 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3311 if (!input.IsValid())
3312 {
3313 return Fail("%s: Operation has invalid inputs", __func__);
3314 }
3315
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003316 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003317 if (!output)
3318 {
3319 return Fail("%s: Could not read output 0", __func__);
3320 }
3321
3322 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003323
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003324 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003325 if (!axisOperand)
3326 {
3327 return Fail("%s: Could not read input 1", __func__);
3328 }
3329
3330 std::vector<int32_t> axis;
3331 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3332 {
3333 return Fail("%s: Input 1 has invalid values", __func__);
3334 }
3335
3336 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3337
3338 // Convert the axis to unsigned int and remove duplicates.
3339 unsigned int rank = inputInfo.GetNumDimensions();
3340 std::set<unsigned int> uniqueAxis;
3341 std::transform(axis.begin(), axis.end(),
3342 std::inserter(uniqueAxis, uniqueAxis.begin()),
3343 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3344
3345 // Get the "keep dims" flag.
3346 int32_t keepDims = 0;
3347 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3348 {
3349 return Fail("%s: Could not read input 2", __func__);
3350 }
3351
3352 armnn::MeanDescriptor descriptor;
3353 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3354 descriptor.m_KeepDims = keepDims > 0;
3355
3356 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003357 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3358 {
3359 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3360 IsMeanSupported,
3361 data.m_Backends,
3362 isSupported,
3363 inputInfo,
3364 outputInfo,
3365 descriptor);
3366 };
3367
3368 if(!IsDynamicTensor(outputInfo))
3369 {
3370 validateFunc(outputInfo, isSupported);
3371 }
3372 else
3373 {
3374 isSupported = AreDynamicTensorsSupported();
3375 }
3376
Mike Kelly46272802019-08-14 17:00:48 +01003377 if (!isSupported)
3378 {
3379 return false;
3380 }
3381
3382 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3383 assert(layer != nullptr);
3384 input.Connect(layer->GetInputSlot(0));
3385
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003386 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003387}
3388
3389template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003390 typename HalOperation = typename HalPolicy::Operation,
3391 typename HalModel = typename HalPolicy::Model>
3392bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003393{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003394 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003395
3396 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3397 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3398
3399 if (!input0.IsValid() || !input1.IsValid())
3400 {
3401 return Fail("%s: Operation has invalid inputs", __func__);
3402 }
3403
3404 // The FuseActivation parameter is always the input index 2
3405 // and it should be optional
3406 ActivationFn activationFunction;
3407 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3408 {
3409 return Fail("%s: Operation has invalid inputs", __func__);
3410 }
3411
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003412 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003413
3414 if (outputOperand == nullptr)
3415 {
3416 return false;
3417 }
3418
3419 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003420
3421 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003422 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3423 {
3424 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3425 IsMultiplicationSupported,
3426 data.m_Backends,
3427 isSupported,
3428 input0.GetTensorInfo(),
3429 input1.GetTensorInfo(),
3430 outputInfo);
3431 };
3432
3433 if(!IsDynamicTensor(outputInfo))
3434 {
3435 validateFunc(outputInfo, isSupported);
3436 }
3437 else
3438 {
3439 isSupported = AreDynamicTensorsSupported();
3440 }
3441
Mike Kelly46272802019-08-14 17:00:48 +01003442 if (!isSupported)
3443 {
3444 return false;
3445 }
3446
3447 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
Mike Kelly46272802019-08-14 17:00:48 +01003448
Kevin Mayfcf2a152020-09-08 16:06:32 +01003449 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3450 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01003451 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003452 return false;
3453 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01003454
Kevin Mayfcf2a152020-09-08 16:06:32 +01003455 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3456 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003457}
3458
3459template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003460 typename HalOperation = typename HalPolicy::Operation,
3461 typename HalModel = typename HalPolicy::Model>
3462bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003463{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003464 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003465
Mike Kelly3c673942019-07-25 09:26:06 +01003466 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3467 if (!input.IsValid())
3468 {
3469 return Fail("%s: Operation has invalid inputs", __func__);
3470 }
3471
3472 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3473 unsigned int rank = inputInfo.GetNumDimensions();
3474
3475 armnn::PadDescriptor descriptor;
3476 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3477 {
3478 return Fail("%s: Could not convert paddings", __func__);
3479 }
3480
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003481 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3482 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003483 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3484 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3485 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003486 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003487 {
3488 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3489 }
3490
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003491 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003492 if (!output)
3493 {
3494 return Fail("%s: Could not read output", __func__);
3495 }
3496
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003497 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003498
3499 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003500 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3501 {
3502 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3503 IsPadSupported,
3504 data.m_Backends,
3505 isSupported,
3506 inputInfo,
3507 outputInfo,
3508 descriptor);
3509 };
3510
3511 if(!IsDynamicTensor(outputInfo))
3512 {
3513 validateFunc(outputInfo, isSupported);
3514 }
3515 else
3516 {
3517 isSupported = AreDynamicTensorsSupported();
3518 }
3519
Mike Kelly3c673942019-07-25 09:26:06 +01003520 if (!isSupported)
3521 {
3522 return false;
3523 }
3524
3525 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3526 assert(layer != nullptr);
3527 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003528
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003529 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003530}
3531
Mike Kelly0a879362019-07-29 16:56:31 +01003532template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003533 typename HalOperation = typename HalPolicy::Operation,
3534 typename HalModel = typename HalPolicy::Model>
3535bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003536{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003537 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003538
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003539 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3540 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3541 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003542
3543 if (inputOperand == nullptr
3544 || requestedShapeOperand == nullptr
3545 || outputOperand == nullptr)
3546 {
3547 return Fail("%s: Operation has invalid inputs", __func__);
3548 }
3549
3550 if (requestedShapeOperand->dimensions.size() != 1)
3551 {
3552 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3553 __func__, requestedShapeOperand->dimensions.size());
3554 }
3555
3556 std::vector<int32_t> targetDimensions;
3557 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3558 {
3559 return Fail("%s: Could not read values of input 1", __func__);
3560 }
3561
3562 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3563
3564 Shape requestedShape;
3565 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3566 // function that resolves these values into a fully specified tensor shape.
3567 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3568 {
3569 return Fail("%s: Failed to resolve the requested shape", __func__);
3570 }
3571
Mike Kelly46272802019-08-14 17:00:48 +01003572 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3573 if (!input.IsValid())
3574 {
3575 return Fail("%s: Could not read input 0", __func__);
3576 }
3577
3578 armnn::ReshapeDescriptor reshapeDescriptor;
3579 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3580 requestedShape.dimensions.data());
3581
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003582 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3583
Mike Kelly46272802019-08-14 17:00:48 +01003584 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003585 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3586 {
3587 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3588 IsReshapeSupported,
3589 data.m_Backends,
3590 isSupported,
3591 input.GetTensorInfo(),
3592 outputInfo,
3593 reshapeDescriptor);
3594 };
3595
3596 if(!IsDynamicTensor(outputInfo))
3597 {
3598 validateFunc(outputInfo, isSupported);
3599 }
3600 else
3601 {
3602 isSupported = AreDynamicTensorsSupported();
3603 }
3604
Mike Kelly46272802019-08-14 17:00:48 +01003605 if (!isSupported)
3606 {
3607 return false;
3608 }
3609
3610 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3611 assert(layer != nullptr);
3612 input.Connect(layer->GetInputSlot(0));
3613
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003614 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003615}
3616
3617template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003618 typename HalOperation = typename HalPolicy::Operation,
3619 typename HalModel = typename HalPolicy::Model>
3620bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003621{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003622 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003623
Mike Kelly0a879362019-07-29 16:56:31 +01003624 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3625 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3626
3627 if (!input0.IsValid() || !input1.IsValid())
3628 {
3629 return Fail("%s: Operation has invalid inputs", __func__);
3630 }
3631
3632 // The FuseActivation parameter is always the input index 2
3633 // and it should be optional
3634 ActivationFn activationFunction;
3635 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3636 {
3637 return Fail("%s: Operation has invalid inputs", __func__);
3638 }
3639
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003640 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003641 if (!output)
3642 {
3643 return Fail("%s: Could not read output 0", __func__);
3644 }
3645
3646 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003647
3648 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003649 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3650 {
3651 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3652 IsSubtractionSupported,
3653 data.m_Backends,
3654 isSupported,
3655 input0.GetTensorInfo(),
3656 input1.GetTensorInfo(),
3657 outputInfo);
3658 };
3659
3660 if(IsDynamicTensor(outputInfo))
3661 {
3662 isSupported = AreDynamicTensorsSupported();
3663 }
3664 else
3665 {
3666 validateFunc(outputInfo, isSupported);
3667 }
3668
Mike Kelly0a879362019-07-29 16:56:31 +01003669 if (!isSupported)
3670 {
3671 return false;
3672 }
3673
3674 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
Mike Kelly0a879362019-07-29 16:56:31 +01003675
Kevin Mayfcf2a152020-09-08 16:06:32 +01003676 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3677 if (!isReshapeSupported)
Mike Kelly0a879362019-07-29 16:56:31 +01003678 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003679 return false;
Mike Kelly0a879362019-07-29 16:56:31 +01003680 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003681 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3682 data, nullptr, validateFunc, activationFunction);
Mike Kelly0a879362019-07-29 16:56:31 +01003683}
3684
Finn Williams23b87b32019-07-30 11:44:05 +01003685template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003686 typename HalOperation = typename HalPolicy::Operation,
3687 typename HalModel = typename HalPolicy::Model>
3688bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003689{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003690 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003691
3692 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3693 if (!input.IsValid())
3694 {
3695 return Fail("%s: Operation has invalid inputs", __func__);
3696 }
3697
3698 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3699 unsigned int rank = inputInfo.GetNumDimensions();
3700 if (rank > 4)
3701 {
3702 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3703 }
3704
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003705 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003706 if (!output)
3707 {
3708 return Fail("%s: Could not read output 0", __func__);
3709 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003710
3711 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003712 {
3713 return Fail("%s: Dynamic output tensors are not supported", __func__);
3714 }
3715
3716 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3717 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003718 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003719
3720 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3721
3722 std::vector<int32_t> axis;
3723 if (!axisOperand)
3724 {
3725 axis.assign(dimensionSequence,
3726 dimensionSequence + rank);
3727 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003728 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003729 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003730 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003731 }
3732
3733 std::vector<uint32_t> outputDims;
3734 for (unsigned int i = 0; i < rank; i++)
3735 {
3736 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3737 auto currentDimension = inputInfo.GetShape()[i];
3738 if (skipSqueeze || currentDimension != 1)
3739 {
3740 outputDims.push_back(currentDimension);
3741 }
3742 }
3743
3744 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3745
3746 armnn::TensorInfo outputInfo = inputInfo;
3747 outputInfo.SetShape(outShape);
3748
3749 armnn::ReshapeDescriptor reshapeDesc;
3750 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3751
3752 bool isSupported = false;
3753 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3754 IsReshapeSupported,
3755 data.m_Backends,
3756 isSupported,
3757 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003758 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003759 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003760
Mike Kelly46272802019-08-14 17:00:48 +01003761 if (!isSupported)
3762 {
3763 return false;
3764 }
3765
3766 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3767 assert(layer != nullptr);
3768 input.Connect(layer->GetInputSlot(0));
3769
3770 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3771}
3772
3773template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003774 typename HalOperation = typename HalPolicy::Operation,
3775 typename HalModel = typename HalPolicy::Model>
3776bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003777{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003778 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003779
3780 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3781 if (!input.IsValid())
3782 {
3783 return Fail("%s: Operation has invalid inputs", __func__);
3784 }
3785
3786 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3787 unsigned int rank = inputInfo.GetNumDimensions();
3788 if (rank > 4)
3789 {
3790 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3791 }
3792
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003793 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003794 if (!output)
3795 {
3796 return Fail("%s: Could not read output 0", __func__);
3797 }
3798
3799 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003800
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003801 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3802 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3803 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003804
3805 std::vector<int32_t> beginValues;
3806 std::vector<int32_t> endValues;
3807 std::vector<int32_t> stridesValues;
3808
3809 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003810 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003811 {
3812 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3813 {
3814 return false;
3815 }
3816
3817 if (operandValues.size() != rank)
3818 {
3819 return false;
3820 }
3821
3822 return true;
3823 };
3824
3825 if (!ValidateInputOperands(*beginOperand, beginValues)
3826 || !ValidateInputOperands(*endOperand, endValues)
3827 || !ValidateInputOperands(*stridesOperand, stridesValues))
3828 {
3829 return Fail("%s: Operation has invalid input operand", __func__);
3830 }
3831
3832 // Stride cannot have value '0'
3833 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3834 {
3835 return Fail("%s: Stride must be non-zero value.", __func__);
3836 }
3837
3838 armnn::StridedSliceDescriptor descriptor;
3839 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3840 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3841 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3842 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3843
3844 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3845 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3846 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3847 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3848 {
3849 return Fail("%s: Operation has invalid inputs", __func__);
3850 }
3851
3852 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003853 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3854 {
3855 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3856 IsStridedSliceSupported,
3857 data.m_Backends,
3858 isSupported,
3859 inputInfo,
3860 outputInfo,
3861 descriptor);
3862 };
3863
3864 if(IsDynamicTensor(outputInfo))
3865 {
3866 isSupported = AreDynamicTensorsSupported();
3867 }
3868 else
3869 {
3870 validateFunc(outputInfo, isSupported);
3871 }
3872
Mike Kelly46272802019-08-14 17:00:48 +01003873 if (!isSupported)
3874 {
3875 return false;
3876 }
3877
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003878 // Check if slice can fit in a inferred output
3879 armnn::TensorShape inputShape = inputInfo.GetShape();
3880 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3881 {
3882 int stride = descriptor.m_Stride[i];
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003883
3884 if (descriptor.m_ShrinkAxisMask & (1 << i))
3885 {
3886 // If the difference between the start point and the end point of the slice on an axis being shrunk
3887 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3888 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3889 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3890 {
3891 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3892 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003893
3894 if(stride < 0)
3895 {
3896 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3897 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003898 }
3899 }
3900
Mike Kelly46272802019-08-14 17:00:48 +01003901 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3902 assert(layer != nullptr);
3903 input.Connect(layer->GetInputSlot(0));
3904
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003905 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003906}
3907
3908template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003909 typename HalOperation = typename HalPolicy::Operation,
3910 typename HalModel = typename HalPolicy::Model>
3911bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003912{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003913 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003914 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003915
3916 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3917 if (!input.IsValid())
3918 {
3919 return Fail("%s: Operation has invalid inputs", __func__);
3920 }
3921
3922 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3923 unsigned int rank = inputInfo.GetNumDimensions();
3924 if (rank > 4)
3925 {
3926 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3927 }
3928
3929 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3930 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003931 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003932
3933 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003934 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003935 {
Mike Kelly46272802019-08-14 17:00:48 +01003936 for (unsigned int i = rank; i > 0; i--)
3937 {
Matthew Sloyan9b088d92020-09-14 15:12:55 +01003938 perm[rank - i] = armnn::numeric_cast<int> (i - 1);
Mike Kelly46272802019-08-14 17:00:48 +01003939 }
3940 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003941 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003942 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003943 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003944 }
3945
3946 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3947
Mike Kelly4a956582020-02-28 10:32:09 +00003948 armnn::TransposeDescriptor transposeDesc;
3949 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003950
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003951 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003952 if (!output)
3953 {
3954 return Fail("%s: Could not read output 0", __func__);
3955 }
3956
3957 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3958
3959 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003960 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3961 {
3962 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3963 IsTransposeSupported,
3964 data.m_Backends,
3965 isSupported,
3966 inputInfo,
3967 outputInfo,
3968 transposeDesc);
3969 };
3970
3971 if(IsDynamicTensor(outputInfo))
3972 {
3973 isSupported = AreDynamicTensorsSupported();
3974 }
3975 else
3976 {
3977 validateFunc(outputInfo, isSupported);
3978 }
3979
Mike Kelly46272802019-08-14 17:00:48 +01003980 if (!isSupported)
3981 {
3982 return false;
3983 }
3984
Mike Kelly4a956582020-02-28 10:32:09 +00003985 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003986 assert(layer != nullptr);
3987 input.Connect(layer->GetInputSlot(0));
3988
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003989 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003990}
3991
3992template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003993 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003994 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003995 typename HalModel = typename HalPolicy::Model>
3996bool ConvertBatchToSpaceNd(const HalOperation& operation,
3997 const HalModel& model,
3998 ConversionData& data)
3999{
Finn Williams23b87b32019-07-30 11:44:05 +01004000
4001 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4002 if (!input.IsValid())
4003 {
4004 return Fail("%s: Operation has invalid inputs", __func__);
4005 }
4006
4007 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4008 if (!output)
4009 {
4010 return Fail("%s: Could not read output 0", __func__);
4011 }
4012
4013 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004014
4015 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4016 if (!blockOperand)
4017 {
4018 return Fail("%s: Could not read input 1", __func__);
4019 }
4020
4021 // Convert the block operand to int32
4022 std::vector<int32_t> block;
4023 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4024 {
4025 return Fail("%s: Input 1 has invalid values", __func__);
4026 }
4027
4028 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4029
4030 unsigned int rank = inputInfo.GetNumDimensions();
4031 if (rank != 4)
4032 {
4033 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4034 }
4035
4036 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4037 {
4038 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4039 " greater than or equal to 1", __func__);
4040 }
4041
4042 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4043 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4044 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4045
Kevin May42477c12020-03-26 13:34:14 +00004046 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004047 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004048 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004049 }
4050 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4051 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4052
4053 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004054 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4055 {
4056 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4057 IsBatchToSpaceNdSupported,
4058 data.m_Backends,
4059 isSupported,
4060 inputInfo,
4061 outputInfo,
4062 batchToSpaceNdDesc);
4063 };
4064
4065 if(!IsDynamicTensor(outputInfo))
4066 {
4067 validateFunc(outputInfo, isSupported);
4068 }
4069 else
4070 {
4071 isSupported = AreDynamicTensorsSupported();
4072 }
4073
4074
Finn Williams23b87b32019-07-30 11:44:05 +01004075 if (!isSupported)
4076 {
4077 return false;
4078 }
4079
4080 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4081 assert(layer != nullptr);
4082 input.Connect(layer->GetInputSlot(0));
4083
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004084 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004085}
Mike Kelly0a879362019-07-29 16:56:31 +01004086
Finn Williamsd74c5052019-07-30 17:06:00 +01004087template<typename HalPolicy,
4088 typename HalOperation = typename HalPolicy::Operation,
4089 typename HalOperand = typename HalPolicy::Operand,
4090 typename HalModel = typename HalPolicy::Model>
4091bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4092{
4093 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4094 if (!input.IsValid())
4095 {
4096 return Fail("%s: Operation has invalid inputs", __func__);
4097 }
4098
4099 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4100 unsigned int rank = inputInfo.GetNumDimensions();
4101 unsigned int spatialDim = rank - 2;
4102
4103 if (rank != 4)
4104 {
4105 Fail("%s: Only inputs with rank 4 are supported", __func__);
4106 }
4107
4108 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4109 if (!output)
4110 {
4111 return Fail("%s: Could not read output 0", __func__);
4112 }
4113
4114 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004115
4116 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4117 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4118
4119 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4120 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4121 {
4122 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4123 }
4124
4125 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004126 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4127 {
4128 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4129 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004130 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4131 {
4132 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4133 }
4134
4135 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4136 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4137 {
4138 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4139 }
4140
4141 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4142 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004143 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4144 {
4145 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4146 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004147 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4148 {
4149 int paddingBeforeInput = paddings[i];
4150 int paddingAfterInput = paddings[i + 1];
4151 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4152 {
4153 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4154 }
4155
4156 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4157 }
4158
4159 armnn::SpaceToBatchNdDescriptor descriptor;
4160 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4161 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4162 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4163
Kevin May42477c12020-03-26 13:34:14 +00004164 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004165 {
4166 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4167 }
4168
4169 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004170 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4171 {
4172 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4173 IsSpaceToBatchNdSupported,
4174 data.m_Backends,
4175 isSupported,
4176 inputInfo,
4177 outputInfo,
4178 descriptor);
4179 };
4180
4181 if(IsDynamicTensor(outputInfo))
4182 {
4183 isSupported = AreDynamicTensorsSupported();
4184 }
4185 else
4186 {
4187 validateFunc(outputInfo, isSupported);
4188 }
4189
Finn Williamsd74c5052019-07-30 17:06:00 +01004190 if (!isSupported)
4191 {
4192 return false;
4193 }
4194
4195 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4196 assert(layer != nullptr);
4197 input.Connect(layer->GetInputSlot(0));
4198
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004199 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004200}
4201
saoste01b8471482018-10-10 09:44:51 +01004202} // namespace armnn_driver