blob: f139383e7f179ef633637097df26f94a61d46176 [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
arovir01b0717b52018-09-05 17:03:25 +010026#include <boost/test/tools/floating_point_comparison.hpp>
27
28#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010029#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010030
31namespace armnn_driver
32{
33
34///
35/// Helper classes
36///
37
Kevin Mayec1e5b82020-02-26 17:00:39 +000038#ifdef ARMNN_ANDROID_R
39using OperandType = android::nn::hal::OperandType;
40#endif
41
arovir01b0717b52018-09-05 17:03:25 +010042struct ConversionData
43{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010044 ConversionData(const std::vector<armnn::BackendId>& backends)
45 : m_Backends(backends)
46 , m_Network(nullptr, nullptr)
Finn Williams291a16b2020-08-19 22:54:00 +010047 , m_DynamicInputsEncountered(false)
arovir01b0717b52018-09-05 17:03:25 +010048 {}
49
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010050 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010051 armnn::INetworkPtr m_Network;
52 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
53 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
Finn Williams291a16b2020-08-19 22:54:00 +010054 bool m_DynamicInputsEncountered;
arovir01b0717b52018-09-05 17:03:25 +010055};
56
57class LayerInputHandle
58{
59public:
60 LayerInputHandle();
61 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
62
63 bool IsValid() const;
64
65 void Connect(armnn::IInputSlot& inputSlot);
66
Finn Williamsa4983ce2020-07-23 12:55:12 +010067 void Disconnect(armnn::IInputSlot& inputSlot);
68
arovir01b0717b52018-09-05 17:03:25 +010069 const armnn::TensorInfo& GetTensorInfo() const;
70
71private:
72 armnn::IOutputSlot* m_OutputSlot;
73 bool m_Valid;
74 armnn::TensorInfo m_TensorInfo;
75};
76
77class ConstTensorPin
78{
79public:
80 // Creates an invalid tensor pin (can be used to signal errors)
81 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
82 ConstTensorPin(bool optional = false);
83
84 // @param tensorInfo TensorInfo associated with the tensor.
85 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
86 // the model being converted.
87 // @param numBytes Number of bytes for the tensor data.
88 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
89 const armnn::PermutationVector& mappings);
90
91 ConstTensorPin(const ConstTensorPin& other) = delete;
92 ConstTensorPin(ConstTensorPin&& other) = default;
93
94 bool IsValid() const;
95 bool IsOptional() const;
96
97 const armnn::ConstTensor& GetConstTensor() const;
98 const armnn::ConstTensor* GetConstTensorPtr() const;
99
100private:
101 armnn::ConstTensor m_ConstTensor;
102
103 // Owned memory for swizzled tensor data, only required if the tensor needed
104 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
105 // the pools associated with the model being converted.
106 std::vector<uint8_t> m_SwizzledTensorData;
107
108 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
109 bool m_Optional;
110};
111
112} // namespace armnn_driver
113
114///
115/// Utility functions
116///
117
118namespace
119{
120
121using namespace armnn_driver;
122using namespace android::nn;
123
124// Convenience function to log the reason for failing to convert a model.
125// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
126template<class... Args>
127static bool Fail(const char* formatStr, Args&&... args)
128{
129 ALOGD(formatStr, std::forward<Args>(args)...);
130 return false;
131}
132
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100133// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
134// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
135#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100136try \
137{ \
138 for (auto&& backendId : backends) \
139 { \
140 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
141 if (layerSupportObject) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100142 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100143 std::string reasonIfUnsupported; \
144 supported = \
145 layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
146 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100147 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100148 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100149 } \
150 else \
151 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100152 if (reasonIfUnsupported.size() > 0) \
153 { \
154 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
155 } \
156 else \
157 { \
158 ALOGD("%s: not supported by armnn", funcName); \
159 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100160 } \
161 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100162 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100163 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100164 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100165 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100166 } \
167 if (!supported) \
168 { \
169 ALOGD("%s: not supported by any specified backend", funcName); \
170 } \
171} \
172catch (const armnn::InvalidArgumentException &e) \
173{ \
174 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
175}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100176
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000177template<typename HalOperand>
178armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100179{
180 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
181}
182
Matthew Bentham912b3622019-05-03 15:49:14 +0100183inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100184{
Matthew Bentham912b3622019-05-03 15:49:14 +0100185 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
186 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
187 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100188}
189
Kevin May42477c12020-03-26 13:34:14 +0000190#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100191
Keith Davis71006492020-01-06 17:44:16 +0000192// Support within the 1.2 driver for specific tensor data types
Mike Kellyb5fdf382019-06-11 16:35:25 +0100193inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
194{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000195 return type == V1_2::OperandType::BOOL ||
Sadik Armagan793a70c2020-03-19 13:54:04 +0000196 type == V1_2::OperandType::TENSOR_BOOL8 ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000197 type == V1_2::OperandType::TENSOR_FLOAT16 ||
198 type == V1_2::OperandType::TENSOR_FLOAT32 ||
199 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
Keith Davis71006492020-01-06 17:44:16 +0000200 type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000201 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
202 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100203 type == V1_2::OperandType::TENSOR_INT32;
204}
205
206#endif
207
Kevin May42477c12020-03-26 13:34:14 +0000208#ifdef ARMNN_ANDROID_NN_V1_3
209
210// Support within the 1.3 driver for specific tensor data types
211inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
212{
213 return type == V1_3::OperandType::BOOL ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100214 type == V1_3::OperandType::TENSOR_BOOL8 ||
Kevin May42477c12020-03-26 13:34:14 +0000215 type == V1_3::OperandType::TENSOR_FLOAT16 ||
216 type == V1_3::OperandType::TENSOR_FLOAT32 ||
217 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100218 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
Kevin May42477c12020-03-26 13:34:14 +0000219 type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
220 type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
221 type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
222 type == V1_3::OperandType::TENSOR_INT32;
223}
224
225#endif
226
Mike Kellyb5fdf382019-06-11 16:35:25 +0100227inline bool IsBool(V1_0::Operand)
228{
229 return false;
230}
231
Kevin May42477c12020-03-26 13:34:14 +0000232inline bool Is12OrLaterOperand(V1_0::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100233{
234 return false;
235}
236
Kevin May42477c12020-03-26 13:34:14 +0000237#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100238
239inline bool IsBool(V1_2::Operand operand)
240{
241 return operand.type == V1_2::OperandType::BOOL;
242}
243
Sadik Armagan61113162019-07-25 09:09:40 +0100244/// Checks if a operand is 1_2 Operand
Kevin May42477c12020-03-26 13:34:14 +0000245inline bool Is12OrLaterOperand(V1_2::Operand)
246{
247 return true;
248}
249
250#endif
251
252#ifdef ARMNN_ANDROID_NN_V1_3
253
254inline bool IsBool(V1_3::Operand operand)
255{
256 return operand.type == V1_3::OperandType::BOOL;
257}
258
259/// Checks if a operand is 1_2 Operand
260inline bool Is12OrLaterOperand(V1_3::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100261{
262 return true;
263}
264
Mike Kellyb5fdf382019-06-11 16:35:25 +0100265#endif
266
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100267template<typename LayerHandleType>
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000268armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
269 LayerHandleType& inputLayer,
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100270 armnn::TensorInfo reshapeInfo)
271{
272 armnn::ReshapeDescriptor reshapeDescriptor;
273 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
274
275 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100276 ARMNN_ASSERT(reshapeLayer != nullptr);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100277
278 // Attach the input layer to the reshape layer
279 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
280 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
281
282 return *reshapeLayer;
283}
284
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000285bool BroadcastTensor(LayerInputHandle& input0,
286 LayerInputHandle& input1,
287 armnn::IConnectableLayer* startLayer,
288 ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100289{
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100290 ARMNN_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100291
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100292 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
293 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
294
295 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
296 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
297
298 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100299 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100300 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
301 input0.Connect(startLayer->GetInputSlot(0));
302 input1.Connect(startLayer->GetInputSlot(1));
303
Sadik Armagan64b19b52019-08-19 09:49:58 +0100304 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100305 }
306
307 // Since the number of dimensions do not match then we need to add degenerate dimensions
308 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
309
310 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100311 unsigned int sizeDifference = std::abs(armnn::numeric_cast<int>(inputDimensions0) -
312 armnn::numeric_cast<int>(inputDimensions1));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100313
314 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
315 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
316 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
317
318 const armnn::TensorShape& smallShape = smallInfo.GetShape();
319 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
320 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
321 {
322 reshapedDimensions[i] = smallShape[i - sizeDifference];
323 }
324
325 armnn::TensorInfo reshapedInfo = smallInfo;
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100326 reshapedInfo.SetShape(armnn::TensorShape{ armnn::numeric_cast<unsigned int>(reshapedDimensions.size()),
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100327 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100328
329 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
330 armnn::ReshapeDescriptor reshapeDescriptor;
331
332 bool isSupported = false;
333 FORWARD_LAYER_SUPPORT_FUNC(__func__,
334 IsReshapeSupported,
335 data.m_Backends,
336 isSupported,
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +0000337 smallInfo,
Sadik Armagan64b19b52019-08-19 09:49:58 +0100338 reshapedInfo,
339 reshapeDescriptor);
340 if (!isSupported)
341 {
342 return false;
343 }
344
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100345 ARMNN_ASSERT(data.m_Network != nullptr);
Sadik Armagan64b19b52019-08-19 09:49:58 +0100346 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100347
348 if (input0IsSmaller)
349 {
350 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
351 //
352 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100353 // | |
354 // Reshape |
355 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100356 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100357
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100358 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
359 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100360 }
361 else
362 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100363 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
364 //
365 // Input0 Input1
366 // | |
367 // | Reshape
368 // \ /
369 // StartLayer
370
arovir01b0717b52018-09-05 17:03:25 +0100371 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100372 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100373 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100374
375 return true;
arovir01b0717b52018-09-05 17:03:25 +0100376}
377
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000378void CalcPadding(uint32_t input,
379 uint32_t kernel,
380 uint32_t stride,
381 uint32_t& outPadHead,
382 uint32_t& outPadTail,
arovir01b0717b52018-09-05 17:03:25 +0100383 android::nn::PaddingScheme scheme)
384{
385 int32_t padHead;
386 int32_t padTail;
387 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100388 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
389 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
arovir01b0717b52018-09-05 17:03:25 +0100390}
391
Kevin May42477c12020-03-26 13:34:14 +0000392#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly86b36d42019-07-12 16:39:33 +0100393
394void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
395 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
396{
397 int32_t padHead;
398 int32_t padTail;
399 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100400 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
401 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
Mike Kelly86b36d42019-07-12 16:39:33 +0100402}
403
Mike Kelly26123db2020-01-15 10:02:33 +0000404void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100405 int32_t& outPadTail, android::nn::PaddingScheme scheme)
406{
407 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
408}
409
Mike Kelly86b36d42019-07-12 16:39:33 +0100410#endif
411
Matthew Bentham912b3622019-05-03 15:49:14 +0100412Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100413{
414 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100415 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100416 shape.dimensions = operand.dimensions;
417 shape.scale = operand.scale;
418 shape.offset = operand.zeroPoint;
419 return shape;
420}
421
Kevin May42477c12020-03-26 13:34:14 +0000422#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly46272802019-08-14 17:00:48 +0100423
424Shape GetOperandShape(const V1_2::Operand& operand)
425{
426 Shape shape;
427 shape.type = OperandType(operand.type);
428 shape.dimensions = operand.dimensions;
429 shape.scale = operand.scale;
430 shape.offset = operand.zeroPoint;
431 return shape;
432}
433
434#endif
435
Kevin May42477c12020-03-26 13:34:14 +0000436#ifdef ARMNN_ANDROID_NN_V1_3
437
438Shape GetOperandShape(const V1_3::Operand& operand)
439{
440 Shape shape;
441 shape.type = OperandType(operand.type);
442 shape.dimensions = operand.dimensions;
443 shape.scale = operand.scale;
444 shape.offset = operand.zeroPoint;
445 return shape;
446}
447
448#endif
449
arovir01b0717b52018-09-05 17:03:25 +0100450// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
451// what AndroidNN requires. However for some of the AndroidNN tests the values don't exactly match so
Aron Virginas-Tara0baa172019-08-01 11:24:08 +0100452// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
453// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100454void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000455 const armnn::TensorInfo& weightInfo,
456 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100457{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000458 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100459 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000460 // NOTE: Bias scale is always set to 0 for per-axis quantization and
461 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
462 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100463 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000464 return biasScale * inputInfo.GetQuantizationScale();
465 };
466
467 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
468 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
469
470 biasInfo.SetQuantizationScales(biasScales);
471 biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
472
473 ALOGV("Bias quantization params have been updated for per-axis quantization");
474 }
475 else
476 {
477 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
478 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
479 {
480 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
481 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
482 {
483 ALOGW("Bias quantization scale has been modified to match input * weights");
484 biasInfo.SetQuantizationScale(expectedBiasScale);
485 }
arovir01b0717b52018-09-05 17:03:25 +0100486 }
487 }
488}
489
490// 4D Tensor Permutations
491const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
David Monahan7f492ac2020-10-16 10:36:29 +0100492const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
arovir01b0717b52018-09-05 17:03:25 +0100493const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
494
495// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000496const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
497const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100498
499template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000500armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
501 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100502{
503 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000504 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
arovir01b0717b52018-09-05 17:03:25 +0100505
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100506 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100507
508 // Connect input to swizzle layer
509 input.Connect(layer->GetInputSlot(0));
510
511 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000512 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100513 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
514
515 return *layer;
516}
517
arovir01b0717b52018-09-05 17:03:25 +0100518bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
519 const armnn::TensorShape & outputShape,
520 uint32_t concatDim)
521{
522 // Validate the output shape is correct given the input shapes (which have just been validated)
523 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
524 if (outputShape.GetNumDimensions() != numDimensions)
525 {
526 return Fail("%s: Output shape has wrong number of dimensions", __func__);
527 }
528
529 unsigned int outputSizeAlongConcatenatedDimension = 0;
530 for (unsigned int i = 0; i < inputShapes.size(); i++)
531 {
532 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
533 }
534
535 for (unsigned int i = 0; i < numDimensions; ++i)
536 {
537 if (i == concatDim)
538 {
539 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
540 {
541 return Fail(
542 "%s: Invalid output shape for dimension %d (%d != %d)",
543 __func__,
544 i,
545 outputShape[i],
546 outputSizeAlongConcatenatedDimension);
547 }
548 }
549 else
550 {
551 if (outputShape[i] != inputShapes[0][i])
552 {
553 return Fail("%s: Invalid output shape", __func__);
554 }
555 }
556 }
557
558 return true;
559}
560
561bool RequiresReshape(armnn::TensorShape & inputShape)
562{
563 return inputShape.GetNumDimensions() < 3;
564}
565
arovir01b0717b52018-09-05 17:03:25 +0100566void SwizzleInputs(armnn::INetwork& network,
567 std::vector<LayerInputHandle>& inputs,
568 std::vector<armnn::TensorShape>& inputShapes,
569 const armnn::PermutationVector& mapping)
570{
571 if (!mapping.IsEqual(IdentityPermutation4D))
572 {
573 size_t nInputs = inputs.size();
574 for (size_t i=0; i<nInputs; ++i)
575 {
576 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000577 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100578 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
579 auto& outputInfo = outputSlot.GetTensorInfo();
580 // replace inputs with the swizzled ones
581 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
582 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
583 }
584 }
585}
586
Teresa Charlin185f5882020-04-06 21:59:18 +0100587bool TransposeInputTensors(ConversionData& data,
588 std::vector<LayerInputHandle>& inputs,
589 std::vector<armnn::TensorShape>& inputShapes,
590 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000591{
David Monahan7f492ac2020-10-16 10:36:29 +0100592 // If we have a IdentityPermutation4D or IdentityPermutation3D then we are not permuting
593 if (!mapping.IsEqual(IdentityPermutation4D) && !mapping.IsEqual(IdentityPermutation3D))
Kevin Mayaed08ac2019-12-12 16:33:31 +0000594 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100595 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000596 size_t nInputs = inputs.size();
597 for (size_t i=0; i<nInputs; ++i)
598 {
599 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000600 armnn::TransposeDescriptor transposeDesc;
601 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100602 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000603
604 bool isSupported = false;
605 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000606 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000607 data.m_Backends,
608 isSupported,
609 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100610 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000611 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000612 if (!isSupported)
613 {
614 return false;
615 }
616
617 }
618 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
619 }
620 return true;
621}
622
623
narpra01f176d5a2018-11-18 20:17:48 +0000624bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
625 int32_t & concatDimension,
626 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100627{
narpra01f176d5a2018-11-18 20:17:48 +0000628 bool needPermute = false;
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100629 ARMNN_ASSERT(numberOfDimensions >= 3);
arovir01b0717b52018-09-05 17:03:25 +0100630
631 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000632 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
633 // or along dimension 0 or 2 for a 3-D tensor.
634 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100635 {
narpra01f176d5a2018-11-18 20:17:48 +0000636 concatDimension = 1;
637 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
638 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100639 }
narpra01f176d5a2018-11-18 20:17:48 +0000640 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100641 {
narpra01f176d5a2018-11-18 20:17:48 +0000642 concatDimension = 0;
643 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
644 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100645 }
David Monahan7f492ac2020-10-16 10:36:29 +0100646 // 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
647 // permutation identity to only have 3 dimensions
648 else if (numberOfDimensions == 3 && concatDimension == 2)
649 {
650 permutationPair = std::make_pair(IdentityPermutation3D, IdentityPermutation3D);
651 }
narpra01f176d5a2018-11-18 20:17:48 +0000652 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100653}
654
655} // anonymous namespace
656
657namespace armnn_driver
658{
659
660//// Creates an ArmNN activation layer and connects it to the given layer, if the
661//// passed in AndroidNN activation function requires so.
662//// @return The end layer of the sequence of layers built for the given AndroidNN
663//// activation function or nullptr if an error occurred (e.g. unsupported activation).
664//// Note that the end layer matches the input layer if no activation is required
665//// (the sequence of layers has length 1).
666armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
667 ActivationFn activation,
668 armnn::IConnectableLayer* prevLayer,
669 ConversionData& data);
670
671} // namespace armnn_driver
672
673///
674/// Utility templates
675///
676
677namespace armnn_driver
678{
679
680using namespace android::nn;
681
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100682template<typename HalPolicy,
683 typename HalOperand = typename HalPolicy::Operand,
684 typename HalOperation = typename HalPolicy::Operation,
685 typename HalModel = typename HalPolicy::Model>
686const HalOperand* GetInputOperand(const HalOperation& operation,
687 uint32_t inputIndex,
688 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100689 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100690{
691 if (inputIndex >= operation.inputs.size())
692 {
saoste01b8471482018-10-10 09:44:51 +0100693 if (failOnIndexOutOfBounds)
694 {
695 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
696 }
arovir01b0717b52018-09-05 17:03:25 +0100697 return nullptr;
698 }
699
Kevin May42477c12020-03-26 13:34:14 +0000700 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100701 ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
Kevin May42477c12020-03-26 13:34:14 +0000702 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100703}
704
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100705template<typename HalPolicy,
706 typename HalOperand = typename HalPolicy::Operand,
707 typename HalOperation = typename HalPolicy::Operation,
708 typename HalModel = typename HalPolicy::Model>
709const HalOperand* GetOutputOperand(const HalOperation& operation,
710 uint32_t outputIndex,
711 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100712{
713 if (outputIndex >= operation.outputs.size())
714 {
715 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
716 return nullptr;
717 }
718
719 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100720 ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
arovir01b0717b52018-09-05 17:03:25 +0100721
Kevin May42477c12020-03-26 13:34:14 +0000722 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100723}
724
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100725template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100726 typename HalOperand = typename HalPolicy::Operand,
727 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100728const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100729 const HalModel& model,
730 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000731 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100732{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100733 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100734
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100735 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100736 switch (operand.lifetime)
737 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100738 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100739 {
740 // Constant found in model.operandValues
741 valueStart = &model.operandValues[operand.location.offset];
742 break;
743 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100744 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100745 {
746 // Constant specified via a Memory object
747 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
748 break;
749 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100750 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000751 {
752 // An optional input tensor with no values is not an error so should not register as a fail
753 if (optional)
754 {
755 valueStart = nullptr;
756 break;
757 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100758 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000759 }
arovir01b0717b52018-09-05 17:03:25 +0100760 default:
761 {
762 // Unsupported/invalid (e.g. can't get value of an input to the model)
763 Fail("%s: unsupported/invalid operand lifetime: %s",
764 __func__, toString(operand.lifetime).c_str());
765 valueStart = nullptr;
766 }
767 }
768
769 return valueStart;
770}
771
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100772template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100773 typename HalOperation = typename HalPolicy::Operation,
774 typename HalModel = typename HalPolicy::Model,
775 typename HalOperandType = typename HalPolicy::OperandType>
776bool GetOperandType(const HalOperation& operation,
777 uint32_t inputIndex,
778 const HalModel& model,
779 HalOperandType& type)
780{
781 using HalOperand = typename HalPolicy::Operand;
782
783 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
784 if (!operand)
785 {
786 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
787 }
788
789 type = operand->type;
790 return true;
791}
792
793template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000794 typename HalOperand = typename HalPolicy::Operand>
795bool IsOperandConstant(const HalOperand& operand)
796{
797 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
798
799 HalOperandLifeTime lifetime = operand.lifetime;
800
801 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
802 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
803 lifetime == HalOperandLifeTime::NO_VALUE;
804}
805
806template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100807 typename HalOperand = typename HalPolicy::Operand,
808 typename HalModel = typename HalPolicy::Model>
809ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
810 const HalModel& model,
811 const ConversionData& data,
812 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
813 const armnn::TensorShape* overrideTensorShape = nullptr,
814 bool optional = false)
815{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100816 if (!IsOperandTypeSupportedForTensors(operand.type))
817 {
818 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
819 return ConstTensorPin();
820 }
821
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000822 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100823 {
824 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
825 return ConstTensorPin();
826 }
827
828 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
829 if (!valueStart)
830 {
831 if (optional)
832 {
833 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
834 return ConstTensorPin(true);
835 }
836 // mandatory tensor with no values
837 Fail("%s: failed to get operand address", __func__);
838 return ConstTensorPin();
839 }
840
841 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000842 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
843 if (tensorInfo.HasPerAxisQuantization())
844 {
845 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
846 }
847
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100848 if (overrideTensorShape != nullptr)
849 {
850 tensorInfo.SetShape(*overrideTensorShape);
851 }
852 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
853}
854
855template<typename HalPolicy,
856 typename HalOperation = typename HalPolicy::Operation,
857 typename HalModel = typename HalPolicy::Model>
858ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
859 uint32_t inputIndex,
860 const HalModel& model,
861 const ConversionData& data,
862 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
863 const armnn::TensorShape* overrideTensorShape = nullptr,
864 bool optional = false)
865{
866 using HalOperand = typename HalPolicy::Operand;
867
868 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
869 if (!operand)
870 {
871 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
872 return ConstTensorPin();
873 }
874 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
875 model,
876 data,
877 dimensionMappings,
878 overrideTensorShape,
879 optional);
880}
881
882template<typename HalPolicy,
883 typename OutputType,
884 typename HalOperandType = typename HalPolicy::OperandType,
885 typename HalOperation = typename HalPolicy::Operation,
886 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100887bool GetInputScalar(const HalOperation& operation,
888 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100889 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100890 OutputType& outValue,
891 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100892 const ConversionData& data,
893 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100894{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100895 using HalOperand = typename HalPolicy::Operand;
896
897 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100898 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100899 {
900 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
901 }
902
Sadik Armagan813f2302020-05-19 14:10:30 +0100903 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100904 {
905 return Fail("%s: unexpected operand type: %s (should be %s)",
906 __func__, toString(operand->type).c_str(), toString(type).c_str());
907 }
908
Sadik Armagan813f2302020-05-19 14:10:30 +0100909 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100910 {
911 return Fail("%s: incorrect operand location length: %i (should be %i)",
912 __func__, operand->location.length, sizeof(OutputType));
913 }
914
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100915 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100916 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100917 {
918 return Fail("%s: failed to get address for operand", __func__);
919 }
920
Sadik Armagan813f2302020-05-19 14:10:30 +0100921 if(!optional)
922 {
923 outValue = *(static_cast<const OutputType*>(valueAddress));
924 }
925
arovir01b0717b52018-09-05 17:03:25 +0100926 return true;
927}
928
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100929template<typename HalPolicy,
930 typename HalOperation = typename HalPolicy::Operation,
931 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100932bool GetInputInt32(const HalOperation& operation,
933 uint32_t inputIndex,
934 int32_t& outValue,
935 const HalModel& model,
936 const ConversionData& data)
937{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100938 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100939}
940
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100941template<typename HalPolicy,
942 typename HalOperation = typename HalPolicy::Operation,
943 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100944bool GetInputFloat32(const HalOperation& operation,
945 uint32_t inputIndex,
946 float& outValue,
947 const HalModel& model,
948 const ConversionData& data)
949{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100950 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100951}
952
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100953template<typename HalPolicy,
954 typename HalOperation = typename HalPolicy::Operation,
955 typename HalOperandType = typename HalPolicy::OperandType,
956 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100957bool GetInputActivationFunctionImpl(const HalOperation& operation,
958 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100959 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100960 ActivationFn& outActivationFunction,
961 const HalModel& model,
962 const ConversionData& data)
963{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100964 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100965 {
966 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
967 __func__,
968 toString(type).c_str(),
969 toString(OperandType::INT32).c_str(),
970 toString(OperandType::TENSOR_INT32).c_str());
971 }
972
973 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100974 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100975 {
976 return Fail("%s: failed to get activation input value", __func__);
977 }
978 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
979 return true;
980}
981
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100982template<typename HalPolicy,
983 typename HalOperation = typename HalPolicy::Operation,
984 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100985bool GetInputActivationFunction(const HalOperation& operation,
986 uint32_t inputIndex,
987 ActivationFn& outActivationFunction,
988 const HalModel& model,
989 const ConversionData& data)
990{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100991 return GetInputActivationFunctionImpl<HalPolicy>(operation,
992 inputIndex,
993 HalPolicy::OperandType::INT32,
994 outActivationFunction,
995 model,
996 data);
arovir01b0717b52018-09-05 17:03:25 +0100997}
998
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100999template<typename HalPolicy,
1000 typename HalOperation = typename HalPolicy::Operation,
1001 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001002bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
1003 uint32_t inputIndex,
1004 ActivationFn& outActivationFunction,
1005 const HalModel& model,
1006 const ConversionData& data)
1007{
1008 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001009 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1010 inputIndex,
1011 HalPolicy::OperandType::INT32,
1012 outActivationFunction,
1013 model,
1014 data);
arovir01b0717b52018-09-05 17:03:25 +01001015}
1016
1017
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001018template<typename HalPolicy,
1019 typename HalOperation = typename HalPolicy::Operation,
1020 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001021bool GetOptionalInputActivation(const HalOperation& operation,
1022 uint32_t inputIndex,
1023 ActivationFn& activationFunction,
1024 const HalModel& model,
1025 const ConversionData& data)
1026{
1027 if (operation.inputs.size() <= inputIndex)
1028 {
1029 activationFunction = ActivationFn::kActivationNone;
1030 }
1031 else
1032 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001033 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001034 {
1035 return Fail("%s: Operation has invalid inputs", __func__);
1036 }
1037 }
1038 return true;
1039}
1040
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001041template<typename HalPolicy,
1042 typename ConvolutionDescriptor,
1043 typename HalOperation = typename HalPolicy::Operation,
1044 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001045bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1046 uint32_t dilationXIndex,
1047 ConvolutionDescriptor& descriptor,
1048 const HalModel& model,
1049 const ConversionData& data)
1050{
1051 bool success = true;
1052 if (operation.inputs.size() >= dilationXIndex + 2)
1053 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001054 success &= GetInputScalar<HalPolicy>(operation,
1055 dilationXIndex,
1056 HalPolicy::OperandType::INT32,
1057 descriptor.m_DilationX,
1058 model,
1059 data);
1060 success &= GetInputScalar<HalPolicy>(operation,
1061 dilationXIndex + 1,
1062 HalPolicy::OperandType::INT32,
1063 descriptor.m_DilationY,
1064 model,
1065 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001066 }
1067
1068 return success;
1069}
1070
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001071template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001072 typename HalOperation = typename HalPolicy::Operation,
1073 typename HalModel = typename HalPolicy::Model>
1074bool GetOptionalBool(const HalOperation& operation,
1075 uint32_t inputIndex,
1076 const HalModel& model,
1077 const ConversionData& data)
1078{
1079 using HalOperand = typename HalPolicy::Operand;
1080
1081 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1082 if (!operand)
1083 {
1084 return false;
1085 }
1086
1087 if (!IsBool(*operand))
1088 {
1089 return false;
1090 }
1091
1092 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1093 if (!valueAddress)
1094 {
1095 return false;
1096 }
1097
1098 if (*(static_cast<const bool*>(valueAddress)))
1099 {
1100 return true;
1101 }
1102 else
1103 {
1104 return false;
1105 }
1106}
1107
1108template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001109 typename HalOperand = typename HalPolicy::Operand,
1110 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001111bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001112 std::vector<int32_t>& outValues,
1113 const HalModel& model,
1114 const ConversionData& data)
1115{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001116 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001117 {
1118 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1119 }
1120
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001121 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001122 if (!startAddress)
1123 {
1124 return Fail("%s: failed to get operand address", __func__, operand.type);
1125 }
1126
1127 // Check number of bytes is sensible
1128 const uint32_t numBytes = operand.location.length;
1129 if (numBytes % sizeof(int32_t) != 0)
1130 {
1131 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1132 __func__, numBytes, sizeof(int32_t));
1133 }
1134
1135 outValues.resize(numBytes / sizeof(int32_t));
1136 memcpy(outValues.data(), startAddress, numBytes);
1137 return true;
1138}
1139
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001140template<typename HalPolicy,
1141 typename HalOperation = typename HalPolicy::Operation,
1142 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001143bool GetInputPaddingScheme(const HalOperation& operation,
1144 uint32_t inputIndex,
1145 PaddingScheme& outPaddingScheme,
1146 const HalModel& model,
1147 const ConversionData& data)
1148{
1149 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001150 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001151 {
1152 return Fail("%s: failed to get padding scheme input value", __func__);
1153 }
1154
1155 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1156 return true;
1157}
1158
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001159template<typename HalPolicy,
1160 typename HalOperation = typename HalPolicy::Operation,
1161 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001162LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1163 uint32_t inputIndex,
1164 const HalModel& model,
1165 ConversionData& data)
1166{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001167 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001168 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001169 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1170
1171 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001172 if (!operand)
1173 {
1174 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1175 return LayerInputHandle();
1176 }
1177
1178 if (!IsOperandTypeSupportedForTensors(operand->type))
1179 {
1180 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1181 return LayerInputHandle();
1182 }
1183
Sadik Armagan44bcc022019-06-18 17:21:36 +01001184 try
arovir01b0717b52018-09-05 17:03:25 +01001185 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001186 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001187 if (IsDynamicTensor(operandTensorInfo))
1188 {
1189 Fail("%s: dynamic input tensors are not supported", __func__);
1190 return LayerInputHandle();
1191 }
arovir01b0717b52018-09-05 17:03:25 +01001192
Sadik Armagan44bcc022019-06-18 17:21:36 +01001193 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001194 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001195 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001196 {
1197 // NOTE: We must check whether we can support the input tensor on at least one
1198 // of the provided backends; otherwise we cannot convert the operation
1199 bool isInputSupported = false;
1200 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1201 IsInputSupported,
1202 data.m_Backends,
1203 isInputSupported,
1204 operandTensorInfo);
1205
1206 if (!isInputSupported)
1207 {
1208 Fail("%s: unsupported input tensor", __func__);
1209 return LayerInputHandle();
1210 }
1211
1212 BOOST_FALLTHROUGH; // intentional fallthrough
1213 }
1214 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001215 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001216 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001217 // The tensor is either an operand internal to the model, or a model input.
1218 // It can be associated with an ArmNN output slot for an existing layer.
1219
1220 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1221 const uint32_t operandIndex = operation.inputs[inputIndex];
1222 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001223 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001224 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001225 case HalOperandLifeTime::CONSTANT_REFERENCE:
1226 {
1227 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1228 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1229 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001230 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001231 bool isSupported = false;
1232 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1233 IsConstantSupported,
1234 data.m_Backends,
1235 isSupported,
1236 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001237 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001238 {
1239 return LayerInputHandle();
1240 }
1241
1242 armnn::IConnectableLayer* constantLayer =
1243 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1244 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1245 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1246
1247 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1248 }
1249 else
1250 {
1251 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001252 return LayerInputHandle();
1253 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001254 break;
arovir01b0717b52018-09-05 17:03:25 +01001255 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001256 default:
arovir01b0717b52018-09-05 17:03:25 +01001257 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001258 // Unsupported lifetime for an input tensor
1259 Fail("%s: unsupported lifetime for input tensor: %s",
1260 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001261 return LayerInputHandle();
1262 }
arovir01b0717b52018-09-05 17:03:25 +01001263 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001264 }
1265 catch (UnsupportedOperand<HalOperandType>& e)
1266 {
1267 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1268 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001269 }
1270}
1271
Kevin May42477c12020-03-26 13:34:14 +00001272
1273#ifdef ARMNN_ANDROID_NN_V1_3
1274template<typename HalPolicy>
1275LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1276 uint32_t inputIndex,
1277 const::android::hardware::neuralnetworks::V1_3::Model& model,
1278 ConversionData& data)
1279{
1280 using HalOperand = typename HalPolicy::Operand;
1281 using HalOperandType = typename HalPolicy::OperandType;
1282 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1283
1284 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1285 if (!operand)
1286 {
1287 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1288 return LayerInputHandle();
1289 }
1290
1291 if (!IsOperandTypeSupportedForTensors(operand->type))
1292 {
1293 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1294 return LayerInputHandle();
1295 }
1296
1297 try
1298 {
1299 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Finn Williams9a044412020-08-17 19:08:35 +01001300
Kevin May42477c12020-03-26 13:34:14 +00001301 if (IsDynamicTensor(operandTensorInfo))
1302 {
Finn Williams291a16b2020-08-19 22:54:00 +01001303 data.m_DynamicInputsEncountered = true;
1304
Finn Williams9a044412020-08-17 19:08:35 +01001305 const uint32_t operandIndex = operation.inputs[inputIndex];
1306
1307 // Check if the dynamic input tensors have been inferred by one of the previous layers
1308 // If not we can't support them
Finn Williams291a16b2020-08-19 22:54:00 +01001309 if (data.m_OutputSlotForOperand.size() >= operandIndex && data.m_OutputSlotForOperand[operandIndex])
Finn Williams9a044412020-08-17 19:08:35 +01001310 {
1311 operandTensorInfo = data.m_OutputSlotForOperand[operandIndex]->GetTensorInfo();
1312 }
1313 else
1314 {
1315 Fail("%s: Type 2 dynamic input tensors are not supported", __func__);
1316 return LayerInputHandle();
1317 }
Kevin May42477c12020-03-26 13:34:14 +00001318 }
1319
1320 switch (operand->lifetime)
1321 {
1322 case HalOperandLifeTime::SUBGRAPH_INPUT:
1323 {
1324 // NOTE: We must check whether we can support the input tensor on at least one
1325 // of the provided backends; otherwise we cannot convert the operation
1326 bool isInputSupported = false;
1327 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1328 IsInputSupported,
1329 data.m_Backends,
1330 isInputSupported,
1331 operandTensorInfo);
1332
1333 if (!isInputSupported)
1334 {
1335 Fail("%s: unsupported input tensor", __func__);
1336 return LayerInputHandle();
1337 }
1338
1339 BOOST_FALLTHROUGH; // intentional fallthrough
1340 }
1341 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1342 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1343 {
1344 // The tensor is either an operand internal to the model, or a model input.
1345 // It can be associated with an ArmNN output slot for an existing layer.
1346
1347 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1348 const uint32_t operandIndex = operation.inputs[inputIndex];
1349 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1350 }
1351 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1352 case HalOperandLifeTime::CONSTANT_REFERENCE:
1353 {
1354 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1355 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1356 if (tensorPin.IsValid())
1357 {
1358 bool isSupported = false;
1359 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1360 IsConstantSupported,
1361 data.m_Backends,
1362 isSupported,
1363 tensorPin.GetConstTensor().GetInfo());
1364 if (!isSupported)
1365 {
1366 return LayerInputHandle();
1367 }
1368
1369 armnn::IConnectableLayer* constantLayer =
1370 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1371 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1372 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1373
1374 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1375 }
1376 else
1377 {
1378 Fail("%s: invalid operand tensor", __func__);
1379 return LayerInputHandle();
1380 }
1381 break;
1382 }
1383 default:
1384 {
1385 // Unsupported lifetime for an input tensor
1386 Fail("%s: unsupported lifetime for input tensor: %s",
1387 __func__, toString(operand->lifetime).c_str());
1388 return LayerInputHandle();
1389 }
1390 }
1391 }
1392 catch (UnsupportedOperand<HalOperandType>& e)
1393 {
1394 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1395 return LayerInputHandle();
1396 }
1397}
1398#endif
1399
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001400template<typename HalPolicy,
1401 typename HalOperation = typename HalPolicy::Operation,
1402 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001403bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1404 uint32_t operationOutputIndex,
1405 armnn::IConnectableLayer& layer,
1406 uint32_t layerOutputIndex,
1407 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001408 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001409 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001410 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001411 const ActivationFn& activationFunction = ActivationFn::kActivationNone,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001412 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001413{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001414 using HalOperand = typename HalPolicy::Operand;
1415
1416 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001417 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1418 {
1419 return false;
1420 }
1421
1422 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001423 if (overrideOutputInfo == nullptr)
1424 {
1425 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1426 }
1427 else
1428 {
1429 outputSlot.SetTensorInfo(*overrideOutputInfo);
1430 }
1431
Finn Williamsa4983ce2020-07-23 12:55:12 +01001432 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001433 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001434 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001435 // Type one dynamic tensors require the previous layer's output shape for inference
1436 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1437 {
1438 if(!layer.GetInputSlot(inputSlotIndex).GetConnection())
1439 {
1440 return false;
1441 }
1442 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001443 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001444 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001445 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001446 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1447
Sadik Armagandbda4b72020-09-03 11:33:07 +01001448 if(!isSupported)
1449 {
1450 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1451 {
1452 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1453 }
1454 return false;
1455 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001456 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001457
Finn Williamsa4983ce2020-07-23 12:55:12 +01001458 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
Kevin Mayfcf2a152020-09-08 16:06:32 +01001459
1460 if (activationFunction != ActivationFn::kActivationNone)
1461 {
1462 const armnn::TensorInfo& activationOutputInfo = outputSlot.GetTensorInfo();
1463 armnn::IConnectableLayer* const endLayer = ProcessActivation(activationOutputInfo, activationFunction,
1464 &layer, data);
1465
1466 if (!endLayer)
1467 {
1468 return Fail("%s: ProcessActivation failed", __func__);
1469 }
1470
1471 armnn::IOutputSlot& activationOutputSlot = endLayer->GetOutputSlot(layerOutputIndex);
1472 data.m_OutputSlotForOperand[operandIndex] = &activationOutputSlot;
1473 }
1474 else
1475 {
1476 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1477 }
Finn Williamsa4983ce2020-07-23 12:55:12 +01001478
Mike Kellyb5fdf382019-06-11 16:35:25 +01001479 return true;
1480}
1481
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001482template<typename HalPolicy,
1483 typename HalOperation = typename HalPolicy::Operation,
1484 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001485armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1486 uint32_t inputIndex,
1487 const HalModel& model,
1488 ConversionData& data)
1489{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001490 using HalOperand = typename HalPolicy::Operand;
1491
1492 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001493 if (!operand)
1494 {
1495 return armnn::DataLayout::NHWC;
1496 }
1497
1498 if (!IsBool(*operand))
1499 {
1500 return armnn::DataLayout::NHWC;
1501 }
1502
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001503 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001504 if (!valueAddress)
1505 {
1506 return armnn::DataLayout::NHWC;
1507 }
1508
1509 if (*(static_cast<const bool*>(valueAddress)))
1510 {
1511 return armnn::DataLayout::NCHW;
1512 }
1513 else
1514 {
1515 return armnn::DataLayout::NHWC;
1516 }
1517}
1518
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001519template<typename HalPolicy,
1520 typename HalOperation = typename HalPolicy::Operation,
1521 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001522bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1523 uint32_t outputIndex,
1524 armnn::IConnectableLayer& layer,
1525 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001526 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001527 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001528 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
1529 const ActivationFn& activationFunction = ActivationFn::kActivationNone)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001530{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001531 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1532 outputIndex,
1533 layer,
1534 outputIndex,
1535 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001536 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001537 overrideOutputInfo,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001538 validateFunc,
1539 activationFunction);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001540}
1541
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001542template<typename HalPolicy,
1543 typename HalOperation = typename HalPolicy::Operation,
1544 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001545bool ConvertToActivation(const HalOperation& operation,
1546 const char* operationName,
1547 const armnn::ActivationDescriptor& activationDesc,
1548 const HalModel& model,
1549 ConversionData& data)
1550{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001551 using HalOperand = typename HalPolicy::Operand;
1552
1553 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001554 if (!input.IsValid())
1555 {
1556 return Fail("%s: Input 0 is invalid", operationName);
1557 }
1558
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001559 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001560 if (!outputOperand)
1561 {
1562 return false;
1563 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001564
1565 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001566
1567 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001568
1569 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1570 {
1571 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1572 IsActivationSupported,
1573 data.m_Backends,
1574 isSupported,
1575 input.GetTensorInfo(),
1576 outInfo,
1577 activationDesc);
1578 };
1579
1580 if(IsDynamicTensor(outInfo))
1581 {
1582 isSupported = AreDynamicTensorsSupported();
1583 }
1584 else
1585 {
1586 validateFunc(outInfo, isSupported);
1587 }
1588
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001589 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001590 {
1591 return false;
1592 }
1593
1594 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001595 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001596 input.Connect(layer->GetInputSlot(0));
1597
Finn Williamsa4983ce2020-07-23 12:55:12 +01001598 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001599}
1600
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001601template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001602 typename HalOperation = typename HalPolicy::Operation,
1603 typename HalModel = typename HalPolicy::Model>
1604bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1605{
1606 armnn::ActivationDescriptor desc;
1607 desc.m_Function = armnn::ActivationFunction::ReLu;
1608
1609 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1610}
1611
1612template<typename HalPolicy,
1613 typename HalOperation = typename HalPolicy::Operation,
1614 typename HalModel = typename HalPolicy::Model>
1615bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1616{
1617 armnn::ActivationDescriptor desc;
1618 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1619 desc.m_A = 1.0f;
1620 desc.m_B = -1.0f;
1621
1622 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1623}
1624
1625template<typename HalPolicy,
1626 typename HalOperation = typename HalPolicy::Operation,
1627 typename HalModel = typename HalPolicy::Model>
1628bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1629{
1630 armnn::ActivationDescriptor desc;
1631 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1632 desc.m_A = 6.0f;
1633
1634 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1635}
1636
1637template<typename HalPolicy,
1638 typename HalOperation = typename HalPolicy::Operation,
1639 typename HalModel = typename HalPolicy::Model>
1640bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1641{
1642 armnn::ActivationDescriptor desc;
1643 desc.m_Function = armnn::ActivationFunction::TanH;
1644 desc.m_A = 1.0f; // android nn does not support tanH parameters
1645 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1646
1647 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1648}
1649
1650template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001651 typename HalOperation = typename HalPolicy::Operation,
1652 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001653bool ConvertPaddings(const HalOperation& operation,
1654 const HalModel& model,
1655 ConversionData& data,
1656 unsigned int rank,
1657 armnn::PadDescriptor& padDescriptor)
1658{
1659 using HalOperand = typename HalPolicy::Operand;
1660
1661 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1662 if (!paddingsOperand)
1663 {
1664 return Fail("%s: Could not read paddings operand", __func__);
1665 }
1666
1667 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1668 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1669 {
1670 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1671 }
1672
1673 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001674 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1675 {
1676 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1677 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001678
1679 // add padding for each dimension of input tensor.
1680 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1681 {
1682 int paddingBeforeInput = paddings[i];
1683 int paddingAfterInput = paddings[i + 1];
1684
1685 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1686 {
1687 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1688 }
1689
1690 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1691 }
1692
1693 return true;
1694}
1695
1696template<typename HalPolicy,
1697 typename HalOperation = typename HalPolicy::Operation,
1698 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001699bool ConvertPooling2d(const HalOperation& operation,
1700 const char* operationName,
1701 armnn::PoolingAlgorithm poolType,
1702 const HalModel& model,
1703 ConversionData& data)
1704{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001705 using HalOperand = typename HalPolicy::Operand;
1706 using HalOperandType = typename HalPolicy::OperandType;
1707
1708 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001709 if (!input.IsValid())
1710 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001711 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001712 }
1713
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001714 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001715 if (!output)
1716 {
1717 return Fail("%s: Could not read output 0", __func__);
1718 }
1719
1720 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1721 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1722
arovir01b0717b52018-09-05 17:03:25 +01001723 armnn::Pooling2dDescriptor desc;
1724 desc.m_PoolType = poolType;
1725 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001726 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001727
1728 ActivationFn activation;
1729
Sadik Armagan15d63e22019-07-26 16:59:35 +01001730 auto inputSize = operation.inputs.size();
1731
1732 if (inputSize >= 10)
1733 {
1734 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1735 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1736 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1737 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1738 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1739 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1740 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1741 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1742 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1743 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1744 {
1745 return Fail("%s: Operation has invalid inputs", operationName);
1746 }
1747
Kevin May42477c12020-03-26 13:34:14 +00001748 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001749 {
1750 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1751 }
1752 }
1753 else
arovir01b0717b52018-09-05 17:03:25 +01001754 {
1755 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1756 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001757 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1758 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1759 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1760 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1761 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1762 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001763 {
1764 return Fail("%s: Operation has invalid inputs", operationName);
1765 }
1766
Kevin May42477c12020-03-26 13:34:14 +00001767 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001768 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001769 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001770 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001771
1772 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1773 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1774 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1775
1776 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1777 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001778 }
1779
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001780 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001781
1782 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1783 {
1784 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1785 IsPooling2dSupported,
1786 data.m_Backends,
1787 isSupported,
1788 inputInfo,
1789 outputInfo,
1790 desc);
1791
1792 };
1793
1794 if(IsDynamicTensor(outputInfo))
1795 {
1796 isSupported = AreDynamicTensorsSupported();
1797 }
1798 else
1799 {
1800 validateFunc(outputInfo, isSupported);
1801 }
1802
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001803 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001804 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001805 return false;
arovir01b0717b52018-09-05 17:03:25 +01001806 }
arovir01b0717b52018-09-05 17:03:25 +01001807
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001808 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1809 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001810 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001811 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001812 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001813
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001814 input.Connect(pooling2dLayer->GetInputSlot(0));
1815
Finn Williamsa4983ce2020-07-23 12:55:12 +01001816 if (!isSupported)
1817 {
1818 return false;
1819 }
1820
Kevin Mayfcf2a152020-09-08 16:06:32 +01001821 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *pooling2dLayer, model,
1822 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001823}
1824
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001825template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001826 typename HalOperation = typename HalPolicy::Operation,
1827 typename HalModel = typename HalPolicy::Model>
1828bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001829{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001830 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001831
1832 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1833 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1834
1835 if (!input0.IsValid() || !input1.IsValid())
1836 {
1837 return Fail("%s: Operation has invalid inputs", __func__);
1838 }
1839
1840 // The FuseActivation parameter is always the input index 2
1841 // and it should be optional
1842 ActivationFn activationFunction;
1843 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1844 {
1845 return Fail("%s: Operation has invalid inputs", __func__);
1846 }
1847
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001848 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001849 if (!outputOperand)
1850 {
1851 return false;
1852 }
1853
1854 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1855 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1856
1857 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001858
1859 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001860 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1861 {
1862 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1863 IsAdditionSupported,
1864 data.m_Backends,
1865 isSupported,
1866 inputInfo0,
1867 inputInfo1,
1868 outputInfo);
1869 };
1870
1871 if(!IsDynamicTensor(outputInfo))
1872 {
1873 validateFunc(outputInfo, isSupported);
1874 }
1875 else
1876 {
1877 isSupported = AreDynamicTensorsSupported();
1878 }
1879
Mike Kelly46272802019-08-14 17:00:48 +01001880 if (!isSupported)
1881 {
1882 return false;
1883 }
1884
1885 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01001886
Kevin Mayfcf2a152020-09-08 16:06:32 +01001887 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1888 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01001889 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01001890 return false;
1891 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01001892
Kevin Mayfcf2a152020-09-08 16:06:32 +01001893 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
1894 data, nullptr, validateFunc, activationFunction);
1895
Mike Kelly46272802019-08-14 17:00:48 +01001896}
1897
1898template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001899 typename HalOperation = typename HalPolicy::Operation,
1900 typename HalModel = typename HalPolicy::Model>
1901bool ConvertArgMinMax(const HalOperation& operation,
1902 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001903 ConversionData& data,
1904 armnn::ArgMinMaxFunction argMinMaxFunction)
1905{
1906 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1907
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001908 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001909 using HalOperandType = typename HalPolicy::OperandType;
1910
1911 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1912
1913 if (!input0.IsValid())
1914 {
1915 return Fail("%s: Operation has invalid inputs", __func__);
1916 }
1917
1918 int32_t axis;
1919 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1920 {
1921 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1922 }
1923
1924 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1925 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1926
1927 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1928 {
1929 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1930 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1931 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1932 return Fail("%s: Axis must be in range [-n, n)", __func__);
1933 }
1934
1935 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1936 if (!output)
1937 {
1938 return Fail("%s: Could not read output 0", __func__);
1939 }
1940
1941 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1942
1943 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001944
1945 armnn::ArgMinMaxDescriptor descriptor;
1946 descriptor.m_Function = argMinMaxFunction;
1947 descriptor.m_Axis = axis;
1948
1949 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001950
1951 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1952 {
1953 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1954 IsArgMinMaxSupported,
1955 data.m_Backends,
1956 isSupported,
1957 inputInfo0,
1958 outputInfo,
1959 descriptor);
1960 };
1961
1962 if(IsDynamicTensor(outputInfo))
1963 {
1964 isSupported = AreDynamicTensorsSupported();
1965 }
1966 else
1967 {
1968 validateFunc(outputInfo, isSupported);
1969 }
1970
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001971 if (!isSupported)
1972 {
1973 return false;
1974 }
1975
1976 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1977 assert(layer != nullptr);
1978
1979 input0.Connect(layer->GetInputSlot(0));
1980
Finn Williamsa4983ce2020-07-23 12:55:12 +01001981 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001982}
1983
1984template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001985 typename HalOperation = typename HalPolicy::Operation,
1986 typename HalModel = typename HalPolicy::Model>
1987bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001988{
Keith Davis6e4081f2020-09-03 13:17:21 +01001989 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001990 using HalOperandType = typename HalPolicy::OperandType;
1991
1992 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1993 if (operation.inputs.size() <= 1)
1994 {
1995 return Fail("%s: Operation has insufficient arguments", __func__);
1996 }
1997
1998 // Get inputs and outputs
1999 const std::size_t numInputTensors = operation.inputs.size() - 1;
2000
2001 int32_t concatDim;
2002 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
2003 {
2004 return Fail("%s: Operation has invalid inputs", __func__);
2005 }
2006
2007 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2008 if (!outputOperand)
2009 {
2010 return Fail("%s: Operation has no outputs", __func__);
2011 }
2012
Keith Davis6e4081f2020-09-03 13:17:21 +01002013 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
2014 armnn::TensorShape outputShape = outputInfo.GetShape();
2015 const bool isDynamicTensor = IsDynamicTensor(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002016 //
2017 // handle negative concat dims along the lines of tensorflow as described here:
2018 // https://www.tensorflow.org/api_docs/python/tf/concat
2019 // "negative axis refers to axis + rank(values)-th dimension"
2020 //
2021 if (concatDim < 0)
2022 {
2023 concatDim += outputShape.GetNumDimensions();
2024 }
2025
2026 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2027 {
2028 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2029 }
2030
2031 std::vector<LayerInputHandle> inputHandles;
2032 std::vector<armnn::TensorShape> inputShapes;
2033
2034 inputHandles.reserve(numInputTensors);
2035 inputShapes.reserve(numInputTensors);
2036
Keith Davis6e4081f2020-09-03 13:17:21 +01002037 bool inputsHaveBeenReshaped = false;
2038 unsigned int tensorDimensionsAdded = 0;
Mike Kellyb8805202019-07-31 17:25:43 +01002039 for (uint32_t i = 0; i < numInputTensors; ++i)
2040 {
2041 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2042 if (!operand)
2043 {
2044 return Fail("%s: Operation has invalid inputs", __func__);
2045 }
2046
Teresa Charlin3b959602019-10-31 17:05:47 +00002047 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2048 if (!operandInputHandle.IsValid())
2049 {
2050 return Fail("%s: Operation has invalid inputs", __func__);
2051 }
Mike Kellyb8805202019-07-31 17:25:43 +01002052
Keith Davis6e4081f2020-09-03 13:17:21 +01002053 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002054 if (operandShape.GetNumDimensions() == 0)
2055 {
2056 return Fail("%s: Operands with rank 0 are not supported", __func__);
2057 }
2058
2059 if (RequiresReshape(operandShape))
2060 {
2061 inputsHaveBeenReshaped = true;
2062
2063 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2064
2065 // Expand the tensor to three dimensions
2066 if (operandShape.GetNumDimensions() == 2)
2067 {
2068 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2069 tensorDimensionsAdded = 1;
2070 }
2071 else
2072 {
2073 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2074 tensorDimensionsAdded = 2;
2075 }
2076
Kevin Mayaed08ac2019-12-12 16:33:31 +00002077 armnn::ReshapeDescriptor reshapeDescriptor;
2078 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2079
2080 bool isSupported = false;
2081 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2082 IsReshapeSupported,
2083 data.m_Backends,
2084 isSupported,
2085 operandInputHandle.GetTensorInfo(),
2086 reshapeInfo,
2087 reshapeDescriptor);
Keith Davis6e4081f2020-09-03 13:17:21 +01002088
Kevin Mayaed08ac2019-12-12 16:33:31 +00002089 if (!isSupported)
2090 {
2091 return false;
2092 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002093 armnn::IConnectableLayer& newReshape = AddReshapeLayer(*data.m_Network, operandInputHandle, reshapeInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002094
2095 // Point to the reshape operation rather then the input operation
Keith Davis6e4081f2020-09-03 13:17:21 +01002096 operandShape = reshapeInfo.GetShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002097 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2098 }
2099
2100 inputShapes.emplace_back(operandShape);
2101 inputHandles.emplace_back(operandInputHandle);
2102
2103 if (!inputHandles.back().IsValid())
2104 {
2105 return Fail("%s: Operation has invalid inputs", __func__);
2106 }
2107 }
2108
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002109 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002110
2111 if (inputsHaveBeenReshaped)
2112 {
2113 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2114 concatDim += tensorDimensionsAdded;
2115
2116 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2117 if (tensorDimensionsAdded == 1)
2118 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002119 if (IsDynamicTensor(outputInfo))
2120 {
2121 outputShape = armnn::TensorShape({1, 0, 0}, {true, false, false});
2122 }
2123 else
2124 {
2125 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2126 }
Mike Kellyb8805202019-07-31 17:25:43 +01002127 }
2128 else if (tensorDimensionsAdded == 2)
2129 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002130 if (IsDynamicTensor(outputInfo))
2131 {
2132 outputShape = armnn::TensorShape({1, 1, 0}, {true, true, false});
2133 }
2134 else
2135 {
2136 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2137 }
Mike Kellyb8805202019-07-31 17:25:43 +01002138 }
2139 }
2140
2141 // Check if permutations is required and get the pair of permutations required for the concatenation.
2142 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2143 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
Keith Davis6e4081f2020-09-03 13:17:21 +01002144 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
Keith Davis6e4081f2020-09-03 13:17:21 +01002145 bool needPermute = CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(),
2146 concatDim,
2147 permutationPair);
Mike Kellyb8805202019-07-31 17:25:43 +01002148
Keith Davis6e4081f2020-09-03 13:17:21 +01002149 // Only relevant to static tensors as dynamic output tensors will be transposed as a result of inferring from input
2150 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002151 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002152 if (needPermute)
2153 {
2154 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
2155 }
2156
2157 outputInfo.SetShape(outputShape);
Mike Kellyb8805202019-07-31 17:25:43 +01002158 }
Mike Kellyb8805202019-07-31 17:25:43 +01002159 // this is no-op for identity swizzles, otherwise it replaces both
2160 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002161 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002162 {
2163 return false;
2164 }
Mike Kellyb8805202019-07-31 17:25:43 +01002165
2166 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2167 armnn::OriginsDescriptor concatDescriptor;
2168
2169 try
2170 {
2171 // The concat descriptor is always created across the only supported concat dimension
2172 // 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 +01002173 concatDescriptor = armnn::CreateDescriptorForConcatenation(inputShapes.begin(),
2174 inputShapes.end(),
2175 concatDim);
2176 } catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002177 {
2178 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2179 }
2180
2181 // Validate the output shape is correct given the input shapes based on the
2182 // 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 +01002183 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002184 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002185 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2186 {
2187 return Fail("%s: Error validating the output shape for concat", __func__);
2188 }
Mike Kellyb8805202019-07-31 17:25:43 +01002189 }
2190
2191 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2192 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
Keith Davis6e4081f2020-09-03 13:17:21 +01002193 [](const LayerInputHandle& h)->const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
Mike Kellyb8805202019-07-31 17:25:43 +01002194
Keith Davis6e4081f2020-09-03 13:17:21 +01002195 bool isSupported = false;
2196 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported){
2197 FORWARD_LAYER_SUPPORT_FUNC(__func__, IsConcatSupported, data.m_Backends, isSupported, inputTensorInfos,
2198 outputInfo, concatDescriptor);
2199 };
2200
2201 if (!isDynamicTensor)
2202 {
2203 validateFunc(outputInfo, isSupported);
2204 }
2205 else
2206 {
2207 isSupported = AreDynamicTensorsSupported();
2208 }
2209
Mike Kellyb8805202019-07-31 17:25:43 +01002210 if (!isSupported)
2211 {
2212 return false;
2213 }
2214
2215 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2216 assert(layer != nullptr);
2217 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002218 // Connect inputs to the layer
2219 const int numInputSlots = layer->GetNumInputSlots();
2220 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2221 for (int i = 0; i < numInputSlots; ++i)
2222 {
2223 // connect the input directly to the merge (concat) layer
2224 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2225 }
2226
Keith Davis6e4081f2020-09-03 13:17:21 +01002227 // Transpose the output shape
2228 auto transposeOutputShape = [&](){
Mike Kelly4a956582020-02-28 10:32:09 +00002229 armnn::TransposeDescriptor transposeDesc;
2230 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002231 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2232 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2233 permutationPair.second);
Keith Davis6e4081f2020-09-03 13:17:21 +01002234 isSupported = false;
Kevin Mayaed08ac2019-12-12 16:33:31 +00002235 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002236 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002237 data.m_Backends,
2238 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002239 inputTransposeInfo,
2240 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002241 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002242 if (!isSupported)
2243 {
2244 return false;
2245 }
Mike Kellyb8805202019-07-31 17:25:43 +01002246 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Keith Davis6e4081f2020-09-03 13:17:21 +01002247 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network, layer->GetOutputSlot(0),
Mike Kelly4a956582020-02-28 10:32:09 +00002248 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002249 layer = &deswizzleLayer;
Keith Davis6e4081f2020-09-03 13:17:21 +01002250
2251 return true;
2252 };
2253
2254 if (needPermute && !isDynamicTensor)
2255 {
2256 transposeOutputShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002257 }
2258
2259 if (inputsHaveBeenReshaped)
2260 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002261 if (isDynamicTensor)
2262 {
2263 // Infer the output shapes of concat if outputs are type 1 dynamic
David Monahan7f492ac2020-10-16 10:36:29 +01002264 ARMNN_ASSERT(layer->GetOutputSlot(0).IsTensorInfoSet());
Keith Davis6e4081f2020-09-03 13:17:21 +01002265 if (!ValidateConcatOutputShape(inputShapes,
2266 layer->GetOutputSlot(0).GetTensorInfo().GetShape(),
2267 concatDim))
2268 {
2269 return Fail("%s: Error validating the output shape for concat", __func__);
2270 }
2271 transposeOutputShape();
2272 }
2273
Mike Kellyb8805202019-07-31 17:25:43 +01002274 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Mike Kellyb8805202019-07-31 17:25:43 +01002275 // Undo the reshape knowing the amount of dimensions added
2276 if (tensorDimensionsAdded == 1)
2277 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002278 afterConcatInfo.SetShape(
2279 armnn::TensorShape({afterConcatInfo.GetShape()[1], afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002280 }
2281 else if (tensorDimensionsAdded == 2)
2282 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002283 afterConcatInfo.SetShape(armnn::TensorShape({afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002284 }
2285
Kevin Mayaed08ac2019-12-12 16:33:31 +00002286 armnn::ReshapeDescriptor reshapeDescriptor;
2287 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
Keith Davis6e4081f2020-09-03 13:17:21 +01002288 armnn::TensorInfo concatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Kevin Mayaed08ac2019-12-12 16:33:31 +00002289
Keith Davis6e4081f2020-09-03 13:17:21 +01002290 isSupported = false;
2291 auto validateReshapeFunc = [&](const armnn::TensorInfo& afterConcatInfo, bool& isSupported){
2292 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2293 IsReshapeSupported,
2294 data.m_Backends,
2295 isSupported,
2296 concatInfo,
2297 afterConcatInfo,
2298 reshapeDescriptor);
2299 };
2300
2301 if (!IsDynamicTensor(afterConcatInfo))
2302 {
2303 validateReshapeFunc(afterConcatInfo, isSupported);
2304 }
2305 else
2306 {
2307 isSupported = AreDynamicTensorsSupported();
2308 }
2309
Kevin Mayaed08ac2019-12-12 16:33:31 +00002310 if (!isSupported)
2311 {
2312 return false;
2313 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002314 layer = &AddReshapeLayer(*data.m_Network, layer->GetOutputSlot(0), afterConcatInfo);
2315 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
2316 0,
2317 *layer,
2318 model,
2319 data,
2320 nullptr,
2321 validateReshapeFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002322 }
2323
Keith Davis6e4081f2020-09-03 13:17:21 +01002324 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002325}
2326
2327template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002328 typename HalOperation = typename HalPolicy::Operation,
2329 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002330bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2331{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002332 using HalOperand = typename HalPolicy::Operand;
2333 using HalOperandType = typename HalPolicy::OperandType;
2334
2335 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002336 if (!input.IsValid())
2337 {
2338 return Fail("%s: Operation has invalid inputs", __func__);
2339 }
2340
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002341 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002342 if (!output)
2343 {
2344 return Fail("%s: Could not read output 0", __func__);
2345 }
2346
2347 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002348 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002349
2350 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002351 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2352 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002353
2354 if (!weightsPin.IsValid() || !biasPin.IsValid())
2355 {
2356 return Fail("%s: Operation has invalid inputs", __func__);
2357 }
2358
2359 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002360 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002361 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2362
2363 armnn::Convolution2dDescriptor desc;
2364 desc.m_DataLayout = armnn::DataLayout::NHWC;
2365 ActivationFn activation;
2366
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002367 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002368 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002369 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2370 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2371 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2372 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2373 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2374 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002375 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002376 {
2377 return Fail("%s: Operation has invalid inputs", __func__);
2378 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002379 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002380 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002381 {
2382 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002383 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2384 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2385 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002386 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002387 {
2388 return Fail("%s: Operation has invalid inputs", __func__);
2389 }
2390
2391 const uint32_t kernelX = weights.GetShape()[2];
2392 const uint32_t kernelY = weights.GetShape()[1];
2393 const uint32_t inputX = inputInfo.GetShape()[2];
2394 const uint32_t inputY = inputInfo.GetShape()[1];
2395
2396 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2397 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002398 }
2399 else
2400 {
2401 return Fail("%s: Unsupported number of operation inputs", __func__);
2402 }
2403
2404 desc.m_BiasEnabled = true;
2405 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2406
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002407 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002408 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2409 {
2410 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2411 IsConvolution2dSupported,
2412 data.m_Backends,
2413 isSupported,
2414 inputInfo,
2415 outputInfo,
2416 desc,
2417 weights.GetInfo(),
2418 biases);
2419 };
2420
2421 if(!IsDynamicTensor(outputInfo))
2422 {
2423 validateFunc(outputInfo, isSupported);
2424 }
2425 else
2426 {
2427 isSupported = AreDynamicTensorsSupported();
2428 }
2429
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002430 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002431 {
2432 return false;
2433 }
2434
2435 armnn::IConnectableLayer* startLayer =
2436 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2437
2438 if (!startLayer)
2439 {
2440 return Fail("%s: AddConvolution2dLayer failed", __func__);
2441 }
2442
Mike Kellyb5fdf382019-06-11 16:35:25 +01002443 input.Connect(startLayer->GetInputSlot(0));
2444
Kevin Mayfcf2a152020-09-08 16:06:32 +01002445 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2446 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002447}
2448
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002449template<typename HalPolicy,
2450 typename HalOperation = typename HalPolicy::Operation,
2451 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002452bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2453{
2454 using HalOperand = typename HalPolicy::Operand;
2455 using HalOperandType = typename HalPolicy::OperandType;
2456
2457 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2458 if (!input.IsValid() )
2459 {
2460 return Fail("%s: Operation has invalid inputs", __func__);
2461 }
2462
2463 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2464 unsigned int rank = inputInfo.GetNumDimensions();
2465 if (rank != 4)
2466 {
2467 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2468 }
2469
2470 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2471 if (!output)
2472 {
2473 return Fail("%s: Could not read output 0", __func__);
2474 }
2475
2476 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002477
2478 armnn::DepthToSpaceDescriptor descriptor;
2479
2480 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2481 if (descriptor.m_BlockSize <= 1)
2482 {
2483 return Fail("%s: Block size must be at least 1 in all dimensions");
2484 }
2485
2486 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002487 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002488 {
2489 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2490 }
2491
2492 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002493 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2494 {
2495 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2496 IsDepthToSpaceSupported,
2497 data.m_Backends,
2498 isSupported,
2499 inputInfo,
2500 outputInfo,
2501 descriptor);
2502 };
2503
2504 if(!IsDynamicTensor(outputInfo))
2505 {
2506 validateFunc(outputInfo, isSupported);
2507 }
2508 else
2509 {
2510 isSupported = AreDynamicTensorsSupported();
2511 }
2512
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002513 if (!isSupported)
2514 {
2515 return false;
2516 }
2517
2518 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2519 assert(layer != nullptr);
2520 input.Connect(layer->GetInputSlot(0));
2521
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002522 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002523}
2524
2525template<typename HalPolicy,
2526 typename HalOperation = typename HalPolicy::Operation,
2527 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002528bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2529{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002530 using HalOperand = typename HalPolicy::Operand;
2531 using HalOperandType = typename HalPolicy::OperandType;
2532
2533 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002534
2535 if (!input.IsValid())
2536 {
2537 return Fail("%s: Operation has invalid inputs", __func__);
2538 }
2539
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002540 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002541
2542 if (!output)
2543 {
2544 return Fail("%s: Could not read output 0", __func__);
2545 }
2546
2547 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002548 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002549
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002550 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002551 // 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 +01002552 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002553
2554 if (weightsOperand == nullptr)
2555 {
2556 return Fail("%s: Operand is invalid", __func__);
2557 }
2558 armnn::DepthwiseConvolution2dDescriptor desc;
2559 desc.m_DataLayout = armnn::DataLayout::NHWC;
2560
Mike Kellyb5fdf382019-06-11 16:35:25 +01002561 // Reinterpret weight data as [ H, W, I, M ]
2562 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2563 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002564 inputInfo.GetShape()[3],
2565 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002566
2567 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2568 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2569
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002570 const ConstTensorPin weightsPin =
2571 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2572 1,
2573 model,
2574 data,
2575 HWIMToMIHW,
2576 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002577
2578 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002579 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002580
2581 if (!weightsPin.IsValid() || !biasPin.IsValid())
2582 {
2583 return Fail("%s: Operation has invalid inputs", __func__);
2584 }
2585
2586 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2587 armnn::ConstTensor bias = biasPin.GetConstTensor();
2588 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2589
2590 ActivationFn activation;
2591
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002592 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002593 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002594 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2595 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2596 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2597 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2598 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2599 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002600 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002601 {
2602 return Fail("%s: Operation has invalid inputs", __func__);
2603 }
2604 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002605 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002606 {
2607 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002608 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2609 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2610 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002611 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002612 {
2613 return Fail("%s: Operation has invalid inputs", __func__);
2614 }
2615
2616 const uint32_t kernelX = weights.GetShape()[3];
2617 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002618 const uint32_t inputX = inputInfo.GetShape()[2];
2619 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002620
2621 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2622 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2623 }
2624 else
2625 {
2626 return Fail("%s: Unsupported number of operation inputs", __func__);
2627 }
2628
2629 desc.m_BiasEnabled = true;
2630 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2631
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002632 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002633 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2634 {
2635 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2636 IsDepthwiseConvolutionSupported,
2637 data.m_Backends,
2638 isSupported,
2639 inputInfo,
2640 outputInfo,
2641 desc,
2642 weights.GetInfo(),
2643 biases);
2644 };
2645
2646 if(!IsDynamicTensor(outputInfo))
2647 {
2648 validateFunc(outputInfo, isSupported);
2649 }
2650 else
2651 {
2652 isSupported = AreDynamicTensorsSupported();
2653 }
2654
2655
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002656 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002657 {
2658 return false;
2659 }
2660
2661 armnn::IConnectableLayer* startLayer =
2662 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2663 if (!startLayer)
2664 {
2665 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2666 }
2667
Mike Kellyb5fdf382019-06-11 16:35:25 +01002668 input.Connect(startLayer->GetInputSlot(0));
2669
Kevin Mayfcf2a152020-09-08 16:06:32 +01002670 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2671 data, nullptr, validateFunc, activation);
arovir01b0717b52018-09-05 17:03:25 +01002672}
2673
Mike Kelly3c673942019-07-25 09:26:06 +01002674template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002675 typename HalOperation = typename HalPolicy::Operation,
2676 typename HalModel = typename HalPolicy::Model>
2677bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002678{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002679 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002680
2681 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2682 if (!input.IsValid())
2683 {
2684 return Fail("%s: Operation has invalid input", __func__);
2685 }
2686
Sadik Armagan98c0f662019-11-21 15:54:36 +00002687 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2688 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2689 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2690 {
2691 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2692 }
2693
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002694 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002695 if (!outputOperand)
2696 {
2697 return Fail("%s: Operation has invalid outputs", __func__);
2698 }
2699
2700 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002701
2702 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002703 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2704 {
2705 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2706 IsDequantizeSupported,
2707 data.m_Backends,
2708 isSupported,
2709 inputInfo,
2710 outputInfo);
2711 };
2712
2713 if(IsDynamicTensor(outputInfo))
2714 {
2715 isSupported = AreDynamicTensorsSupported();
2716 }
2717 else
2718 {
2719 validateFunc(outputInfo, isSupported);
2720 }
2721
Mike Kelly46272802019-08-14 17:00:48 +01002722 if (!isSupported)
2723 {
2724 return false;
2725 }
2726
2727 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2728 assert(layer != nullptr);
2729 input.Connect(layer->GetInputSlot(0));
2730
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002731 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002732}
2733
2734template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002735 typename HalOperation = typename HalPolicy::Operation,
2736 typename HalModel = typename HalPolicy::Model>
2737bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002738{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002739 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002740
2741 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2742 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2743
2744 if (!input0.IsValid() || !input1.IsValid())
2745 {
2746 return Fail("%s: Operation has invalid inputs", __func__);
2747 }
2748
2749 // The FuseActivation parameter is always the input index 2
2750 // and it should be optional
2751 ActivationFn activationFunction;
2752 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2753 {
2754 return Fail("%s: Operation has invalid inputs", __func__);
2755 }
2756
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002757 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002758 if (!output)
2759 {
2760 return Fail("%s: Could not read output 0", __func__);
2761 }
2762
2763 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002764
2765 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002766 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2767 {
2768 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2769 IsDivisionSupported,
2770 data.m_Backends,
2771 isSupported,
2772 input0.GetTensorInfo(),
2773 input1.GetTensorInfo(),
2774 outputInfo);
2775 };
2776
2777 if(!IsDynamicTensor(outputInfo))
2778 {
2779 validateFunc(outputInfo, isSupported);
2780 }
2781 else
2782 {
2783 isSupported = AreDynamicTensorsSupported();
2784 }
2785
Mike Kelly46272802019-08-14 17:00:48 +01002786 if (!isSupported)
2787 {
2788 return false;
2789 }
2790
2791 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01002792
Kevin Mayfcf2a152020-09-08 16:06:32 +01002793 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2794 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01002795 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01002796 return false;
Mike Kelly46272802019-08-14 17:00:48 +01002797 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01002798
2799 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2800 data, nullptr, validateFunc, activationFunction);
2801
Mike Kelly46272802019-08-14 17:00:48 +01002802}
2803
2804template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002805 typename HalOperation = typename HalPolicy::Operation,
2806 typename HalModel = typename HalPolicy::Model>
2807bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002808{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002809 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002810
2811 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2812 if (!input.IsValid())
2813 {
2814 return Fail("%s: Operation has invalid inputs", __func__);
2815 }
2816
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002817 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002818 if (!outputOperand)
2819 {
2820 return Fail("%s: Operation has invalid outputs", __func__);
2821 }
2822
2823 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002824
2825 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002826 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2827 {
2828 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2829 IsFloorSupported,
2830 data.m_Backends,
2831 isSupported,
2832 input.GetTensorInfo(),
2833 outputInfo);
2834 };
2835
2836 if(!IsDynamicTensor(outputInfo))
2837 {
2838 validateFunc(outputInfo, isSupported);
2839 }
2840 else
2841 {
2842 isSupported = AreDynamicTensorsSupported();
2843 }
2844
Mike Kelly46272802019-08-14 17:00:48 +01002845 if (!isSupported)
2846 {
2847 return false;
2848 }
2849
2850 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2851 assert(layer != nullptr);
2852 input.Connect(layer->GetInputSlot(0));
2853
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002854 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002855}
2856
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002857inline bool IsQSymm8(const V1_0::Operand&)
2858{
2859 return false;
2860}
2861
Kevin May42477c12020-03-26 13:34:14 +00002862#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002863
2864inline bool IsQSymm8(const V1_2::Operand& operand)
2865{
2866 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2867}
2868
2869#endif
2870
Kevin May42477c12020-03-26 13:34:14 +00002871#ifdef ARMNN_ANDROID_NN_V1_3
2872
2873inline bool IsQSymm8(const V1_3::Operand& operand)
2874{
2875 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2876}
2877
2878#endif
2879
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002880enum class DequantizeStatus
2881{
2882 SUCCESS,
2883 NOT_REQUIRED,
2884 INVALID_OPERAND
2885};
2886
2887using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2888
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002889template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002890 typename HalOperation = typename HalPolicy::Operation,
2891 typename HalModel = typename HalPolicy::Model>
2892DequantizeResult DequantizeIfRequired(size_t operand_index,
2893 const HalOperation& operation,
2894 const HalModel& model,
2895 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002896{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002897 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002898
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002899 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002900 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002901 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002902 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002903 }
2904
2905 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2906 {
2907 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002908 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002909 }
2910
2911 const size_t weightsInputIndex = operation.inputs[operand_index];
2912
2913 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2914 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002915 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002916 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002917 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002918 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002919 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2920 {
2921 continue;
2922 }
2923
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002924 size_t outOpIndex = weightsInputIndex + 1;
2925 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002926 {
2927 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002928 }
2929
2930 if (outOpIndex != weightsInputIndex)
2931 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002932 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002933 }
2934
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002935 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002936 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002937
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002938 if (!IsQSymm8(*operand))
2939 {
2940 // Only supporting dequantize from QSYMM8 to FLOAT
2941 break;
2942 }
2943
2944 // Allocate a new buffer for the dequantized data and manually dequantize
2945 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2946 if (!startValue)
2947 {
2948 // Failed to get the operand address
2949 break;
2950 }
2951
2952 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2953 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002954 const float quantizationScale = operand->scale;
2955
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002956 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2957 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2958 {
2959 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002960 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002961 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2962 }
2963
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002964 // Construct tensor info for dequantized ConstTensor
2965 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2966 operand->dimensions.data(),
2967 armnn::DataType::Float32);
2968
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002969 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2970 std::move(tensorInfo),
2971 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002972 }
2973
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002974 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002975}
2976
2977template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002978 typename HalOperation = typename HalPolicy::Operation,
2979 typename HalModel = typename HalPolicy::Model>
2980ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2981 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002982 const ConversionData& data,
2983 size_t operandIndex,
2984 bool optional = false)
2985{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002986 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2987
2988 DequantizeStatus status = std::get<3>(dequantized);
2989 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002990 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002991 case DequantizeStatus::INVALID_OPERAND:
2992 {
2993 // return invalid const tensor pin
2994 return ConstTensorPin();
2995 }
2996 case DequantizeStatus::NOT_REQUIRED:
2997 {
2998 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2999 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
3000 }
3001 case DequantizeStatus::SUCCESS:
3002 default:
3003 {
3004 return ConstTensorPin(
3005 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
3006 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003007 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003008}
3009
3010
Mike Kelly46272802019-08-14 17:00:48 +01003011template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003012 typename HalOperation = typename HalPolicy::Operation,
3013 typename HalModel = typename HalPolicy::Model>
3014bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003015{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003016 using HalOperand = typename HalPolicy::Operand;
3017
Mike Kelly46272802019-08-14 17:00:48 +01003018 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3019 if (!input.IsValid())
3020 {
3021 return Fail("%s: Operation has invalid inputs", __func__);
3022 }
3023
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003024 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003025 if (!output)
3026 {
3027 return Fail("%s: Could not read output 0", __func__);
3028 }
3029
3030 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3031 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3032
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003033 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
3034 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003035
3036 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01003037 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003038 return Fail("%s: Operation has invalid weights", __func__);
3039 }
3040
3041 if (!biasPin.IsValid())
3042 {
3043 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003044 }
3045
3046 armnn::ConstTensor weights = weightsPin.GetConstTensor();
3047 armnn::ConstTensor bias = biasPin.GetConstTensor();
3048 armnn::TensorInfo reshapedInfo = inputInfo;
3049
3050 try
3051 {
3052 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003053 }
3054 catch (const std::exception& e)
3055 {
Mike Kelly46272802019-08-14 17:00:48 +01003056 return Fail("%s: %s", __func__, e.what());
3057 }
3058
3059 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
3060 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
3061
3062 ActivationFn activationFunction;
3063 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3064 {
3065 return Fail("%s: Operation has invalid inputs", __func__);
3066 }
3067
3068 armnn::FullyConnectedDescriptor desc;
3069 desc.m_TransposeWeightMatrix = true;
3070 desc.m_BiasEnabled = true;
3071
3072 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003073 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3074 {
Finn Williams49184462020-10-02 13:28:34 +01003075 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
3076 weights.GetInfo().GetShape(),
3077 outputInfo.GetShape(),
3078 desc.m_TransposeWeightMatrix))
3079 {
3080 isSupported = false;
3081 Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3082 return;
3083 }
3084
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003085 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly46272802019-08-14 17:00:48 +01003086 IsFullyConnectedSupported,
3087 data.m_Backends,
3088 isSupported,
3089 reshapedInfo,
3090 outputInfo,
3091 weights.GetInfo(),
3092 bias.GetInfo(),
3093 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003094 };
3095
3096 if(!IsDynamicTensor(outputInfo))
3097 {
3098 validateFunc(outputInfo, isSupported);
3099 }
3100 else
3101 {
3102 isSupported = AreDynamicTensorsSupported();
3103 }
3104
Mike Kelly46272802019-08-14 17:00:48 +01003105 if (!isSupported)
3106 {
3107 return false;
3108 }
3109
3110 armnn::IConnectableLayer* startLayer =
3111 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
Mike Kelly46272802019-08-14 17:00:48 +01003112
Kevin Mayfcf2a152020-09-08 16:06:32 +01003113 if (inputInfo.GetNumDimensions() > 2U)
Mike Kelly46272802019-08-14 17:00:48 +01003114 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003115 armnn::ReshapeDescriptor reshapeDescriptor;
3116 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
Mike Kelly46272802019-08-14 17:00:48 +01003117
Kevin Mayfcf2a152020-09-08 16:06:32 +01003118 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3119 assert(reshapeLayer != nullptr);
3120 input.Connect(reshapeLayer->GetInputSlot(0));
3121 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3122 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003123 }
3124 else
3125 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003126 input.Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003127 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003128
3129 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3130 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003131}
3132
3133template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003134 typename HalOperation = typename HalPolicy::Operation,
3135 typename HalModel = typename HalPolicy::Model>
3136bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003137{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003138 using HalOperand = typename HalPolicy::Operand;
3139
Mike Kelly999e2092019-08-15 10:46:46 +01003140 if (operation.inputs.size() != 1)
3141 {
3142 return Fail("%s: Optional inputs are not supported", __func__);
3143 }
3144
Mike Kelly46272802019-08-14 17:00:48 +01003145 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3146 if (!input.IsValid())
3147 {
3148 return Fail("%s: Operation has invalid inputs", __func__);
3149 }
3150
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003151 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003152 if (!output)
3153 {
3154 return Fail("%s: Could not read output 0", __func__);
3155 }
3156
3157 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3158 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3159
Mike Kelly46272802019-08-14 17:00:48 +01003160 if (outputInfo.GetNumDimensions() != 4u)
3161 {
3162 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3163 }
3164
3165 armnn::L2NormalizationDescriptor desc;
3166 desc.m_DataLayout = armnn::DataLayout::NHWC;
3167
3168 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003169 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3170 {
3171 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3172 IsL2NormalizationSupported,
3173 data.m_Backends,
3174 isSupported,
3175 inputInfo,
3176 outputInfo,
3177 desc);
3178 };
3179
3180 if(!IsDynamicTensor(outputInfo))
3181 {
3182 validateFunc(outputInfo, isSupported);
3183 }
3184 else
3185 {
3186 isSupported = AreDynamicTensorsSupported();
3187 }
3188
Mike Kelly46272802019-08-14 17:00:48 +01003189 if (!isSupported)
3190 {
3191 return false;
3192 }
3193
3194 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3195 assert(layer != nullptr);
3196 input.Connect(layer->GetInputSlot(0));
3197
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003198 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003199}
3200
3201template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003202 typename HalOperation = typename HalPolicy::Operation,
3203 typename HalModel = typename HalPolicy::Model>
3204bool ConvertLocalResponseNormalization(const HalOperation& operation,
3205 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003206 ConversionData& data)
3207{
Mike Kelly999e2092019-08-15 10:46:46 +01003208 if (operation.inputs.size() != 5)
3209 {
3210 return Fail("%s: Optional inputs are not supported", __func__);
3211 }
3212
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003213 using HalOperand = typename HalPolicy::Operand;
3214 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003215
3216 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3217 if (!input.IsValid())
3218 {
3219 return Fail("%s: Operation has invalid inputs", __func__);
3220 }
3221
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003222 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003223 if (!output)
3224 {
3225 return Fail("%s: Could not read output 0", __func__);
3226 }
3227
3228 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3229 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3230
Mike Kelly46272802019-08-14 17:00:48 +01003231 if (outputInfo.GetNumDimensions() != 4u)
3232 {
3233 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3234 }
3235
3236 armnn::NormalizationDescriptor descriptor;
3237 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3238 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3239 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3240
3241 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003242 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003243 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3244 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3245 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3246 {
3247 return Fail("%s: Operation has invalid inputs", __func__);
3248 }
3249
3250 // ArmNN expects normSize to be the full size of the normalization
3251 // window rather than the radius as in AndroidNN.
3252 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3253
3254 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003255 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3256 {
3257 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3258 IsNormalizationSupported,
3259 data.m_Backends,
3260 isSupported,
3261 inputInfo,
3262 outputInfo,
3263 descriptor);
3264 };
3265
3266 if(!IsDynamicTensor(outputInfo))
3267 {
3268 validateFunc(outputInfo, isSupported);
3269 }
3270 else
3271 {
3272 isSupported = AreDynamicTensorsSupported();
3273 }
3274
Mike Kelly46272802019-08-14 17:00:48 +01003275 if (!isSupported)
3276 {
3277 return false;
3278 }
3279
3280
3281 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3282 assert(layer != nullptr);
3283 input.Connect(layer->GetInputSlot(0));
3284
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003285 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003286}
3287
3288template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003289 typename HalOperation = typename HalPolicy::Operation,
3290 typename HalModel = typename HalPolicy::Model>
3291bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003292{
Mike Kelly46272802019-08-14 17:00:48 +01003293 armnn::ActivationDescriptor desc;
3294 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3295
3296 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3297}
3298
3299template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003300 typename HalOperation = typename HalPolicy::Operation,
3301 typename HalModel = typename HalPolicy::Model>
3302bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003303{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003304 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003305
3306 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3307 if (!input.IsValid())
3308 {
3309 return Fail("%s: Operation has invalid inputs", __func__);
3310 }
3311
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003312 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003313 if (!output)
3314 {
3315 return Fail("%s: Could not read output 0", __func__);
3316 }
3317
3318 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003319
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003320 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003321 if (!axisOperand)
3322 {
3323 return Fail("%s: Could not read input 1", __func__);
3324 }
3325
3326 std::vector<int32_t> axis;
3327 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3328 {
3329 return Fail("%s: Input 1 has invalid values", __func__);
3330 }
3331
3332 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3333
3334 // Convert the axis to unsigned int and remove duplicates.
3335 unsigned int rank = inputInfo.GetNumDimensions();
3336 std::set<unsigned int> uniqueAxis;
3337 std::transform(axis.begin(), axis.end(),
3338 std::inserter(uniqueAxis, uniqueAxis.begin()),
3339 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3340
3341 // Get the "keep dims" flag.
3342 int32_t keepDims = 0;
3343 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3344 {
3345 return Fail("%s: Could not read input 2", __func__);
3346 }
3347
3348 armnn::MeanDescriptor descriptor;
3349 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3350 descriptor.m_KeepDims = keepDims > 0;
3351
3352 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003353 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3354 {
3355 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3356 IsMeanSupported,
3357 data.m_Backends,
3358 isSupported,
3359 inputInfo,
3360 outputInfo,
3361 descriptor);
3362 };
3363
3364 if(!IsDynamicTensor(outputInfo))
3365 {
3366 validateFunc(outputInfo, isSupported);
3367 }
3368 else
3369 {
3370 isSupported = AreDynamicTensorsSupported();
3371 }
3372
Mike Kelly46272802019-08-14 17:00:48 +01003373 if (!isSupported)
3374 {
3375 return false;
3376 }
3377
3378 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3379 assert(layer != nullptr);
3380 input.Connect(layer->GetInputSlot(0));
3381
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003382 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003383}
3384
3385template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003386 typename HalOperation = typename HalPolicy::Operation,
3387 typename HalModel = typename HalPolicy::Model>
3388bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003389{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003390 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003391
3392 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3393 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3394
3395 if (!input0.IsValid() || !input1.IsValid())
3396 {
3397 return Fail("%s: Operation has invalid inputs", __func__);
3398 }
3399
3400 // The FuseActivation parameter is always the input index 2
3401 // and it should be optional
3402 ActivationFn activationFunction;
3403 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3404 {
3405 return Fail("%s: Operation has invalid inputs", __func__);
3406 }
3407
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003408 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003409
3410 if (outputOperand == nullptr)
3411 {
3412 return false;
3413 }
3414
3415 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003416
3417 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003418 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3419 {
3420 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3421 IsMultiplicationSupported,
3422 data.m_Backends,
3423 isSupported,
3424 input0.GetTensorInfo(),
3425 input1.GetTensorInfo(),
3426 outputInfo);
3427 };
3428
3429 if(!IsDynamicTensor(outputInfo))
3430 {
3431 validateFunc(outputInfo, isSupported);
3432 }
3433 else
3434 {
3435 isSupported = AreDynamicTensorsSupported();
3436 }
3437
Mike Kelly46272802019-08-14 17:00:48 +01003438 if (!isSupported)
3439 {
3440 return false;
3441 }
3442
3443 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
Mike Kelly46272802019-08-14 17:00:48 +01003444
3445 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3446 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3447
Kevin Mayfcf2a152020-09-08 16:06:32 +01003448 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3449 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01003450 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003451 return false;
3452 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01003453
Kevin Mayfcf2a152020-09-08 16:06:32 +01003454 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3455 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003456}
3457
3458template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003459 typename HalOperation = typename HalPolicy::Operation,
3460 typename HalModel = typename HalPolicy::Model>
3461bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003462{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003463 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003464
Mike Kelly3c673942019-07-25 09:26:06 +01003465 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3466 if (!input.IsValid())
3467 {
3468 return Fail("%s: Operation has invalid inputs", __func__);
3469 }
3470
3471 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3472 unsigned int rank = inputInfo.GetNumDimensions();
3473
3474 armnn::PadDescriptor descriptor;
3475 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3476 {
3477 return Fail("%s: Could not convert paddings", __func__);
3478 }
3479
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003480 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3481 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003482 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3483 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3484 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003485 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003486 {
3487 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3488 }
3489
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003490 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003491 if (!output)
3492 {
3493 return Fail("%s: Could not read output", __func__);
3494 }
3495
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003496 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003497
3498 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003499 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3500 {
3501 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3502 IsPadSupported,
3503 data.m_Backends,
3504 isSupported,
3505 inputInfo,
3506 outputInfo,
3507 descriptor);
3508 };
3509
3510 if(!IsDynamicTensor(outputInfo))
3511 {
3512 validateFunc(outputInfo, isSupported);
3513 }
3514 else
3515 {
3516 isSupported = AreDynamicTensorsSupported();
3517 }
3518
Mike Kelly3c673942019-07-25 09:26:06 +01003519 if (!isSupported)
3520 {
3521 return false;
3522 }
3523
3524 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3525 assert(layer != nullptr);
3526 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003527
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003528 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003529}
3530
Mike Kelly0a879362019-07-29 16:56:31 +01003531template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003532 typename HalOperation = typename HalPolicy::Operation,
3533 typename HalModel = typename HalPolicy::Model>
3534bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003535{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003536 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003537
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003538 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3539 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3540 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003541
3542 if (inputOperand == nullptr
3543 || requestedShapeOperand == nullptr
3544 || outputOperand == nullptr)
3545 {
3546 return Fail("%s: Operation has invalid inputs", __func__);
3547 }
3548
3549 if (requestedShapeOperand->dimensions.size() != 1)
3550 {
3551 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3552 __func__, requestedShapeOperand->dimensions.size());
3553 }
3554
3555 std::vector<int32_t> targetDimensions;
3556 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3557 {
3558 return Fail("%s: Could not read values of input 1", __func__);
3559 }
3560
3561 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3562
3563 Shape requestedShape;
3564 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3565 // function that resolves these values into a fully specified tensor shape.
3566 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3567 {
3568 return Fail("%s: Failed to resolve the requested shape", __func__);
3569 }
3570
Mike Kelly46272802019-08-14 17:00:48 +01003571 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3572 if (!input.IsValid())
3573 {
3574 return Fail("%s: Could not read input 0", __func__);
3575 }
3576
3577 armnn::ReshapeDescriptor reshapeDescriptor;
3578 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3579 requestedShape.dimensions.data());
3580
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003581 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3582
Mike Kelly46272802019-08-14 17:00:48 +01003583 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003584 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3585 {
3586 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3587 IsReshapeSupported,
3588 data.m_Backends,
3589 isSupported,
3590 input.GetTensorInfo(),
3591 outputInfo,
3592 reshapeDescriptor);
3593 };
3594
3595 if(!IsDynamicTensor(outputInfo))
3596 {
3597 validateFunc(outputInfo, isSupported);
3598 }
3599 else
3600 {
3601 isSupported = AreDynamicTensorsSupported();
3602 }
3603
Mike Kelly46272802019-08-14 17:00:48 +01003604 if (!isSupported)
3605 {
3606 return false;
3607 }
3608
3609 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3610 assert(layer != nullptr);
3611 input.Connect(layer->GetInputSlot(0));
3612
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003613 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003614}
3615
3616template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003617 typename HalOperation = typename HalPolicy::Operation,
3618 typename HalModel = typename HalPolicy::Model>
3619bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003620{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003621 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003622
Mike Kelly0a879362019-07-29 16:56:31 +01003623 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3624 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3625
3626 if (!input0.IsValid() || !input1.IsValid())
3627 {
3628 return Fail("%s: Operation has invalid inputs", __func__);
3629 }
3630
3631 // The FuseActivation parameter is always the input index 2
3632 // and it should be optional
3633 ActivationFn activationFunction;
3634 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3635 {
3636 return Fail("%s: Operation has invalid inputs", __func__);
3637 }
3638
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003639 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003640 if (!output)
3641 {
3642 return Fail("%s: Could not read output 0", __func__);
3643 }
3644
3645 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003646
3647 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003648 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3649 {
3650 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3651 IsSubtractionSupported,
3652 data.m_Backends,
3653 isSupported,
3654 input0.GetTensorInfo(),
3655 input1.GetTensorInfo(),
3656 outputInfo);
3657 };
3658
3659 if(IsDynamicTensor(outputInfo))
3660 {
3661 isSupported = AreDynamicTensorsSupported();
3662 }
3663 else
3664 {
3665 validateFunc(outputInfo, isSupported);
3666 }
3667
Mike Kelly0a879362019-07-29 16:56:31 +01003668 if (!isSupported)
3669 {
3670 return false;
3671 }
3672
3673 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
Mike Kelly0a879362019-07-29 16:56:31 +01003674
3675 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3676 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3677
Kevin Mayfcf2a152020-09-08 16:06:32 +01003678 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3679 if (!isReshapeSupported)
Mike Kelly0a879362019-07-29 16:56:31 +01003680 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003681 return false;
Mike Kelly0a879362019-07-29 16:56:31 +01003682 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003683 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3684 data, nullptr, validateFunc, activationFunction);
Mike Kelly0a879362019-07-29 16:56:31 +01003685}
3686
Finn Williams23b87b32019-07-30 11:44:05 +01003687template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003688 typename HalOperation = typename HalPolicy::Operation,
3689 typename HalModel = typename HalPolicy::Model>
3690bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003691{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003692 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003693
3694 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3695 if (!input.IsValid())
3696 {
3697 return Fail("%s: Operation has invalid inputs", __func__);
3698 }
3699
3700 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3701 unsigned int rank = inputInfo.GetNumDimensions();
3702 if (rank > 4)
3703 {
3704 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3705 }
3706
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003707 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003708 if (!output)
3709 {
3710 return Fail("%s: Could not read output 0", __func__);
3711 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003712
3713 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003714 {
3715 return Fail("%s: Dynamic output tensors are not supported", __func__);
3716 }
3717
3718 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3719 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003720 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003721
3722 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3723
3724 std::vector<int32_t> axis;
3725 if (!axisOperand)
3726 {
3727 axis.assign(dimensionSequence,
3728 dimensionSequence + rank);
3729 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003730 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003731 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003732 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003733 }
3734
3735 std::vector<uint32_t> outputDims;
3736 for (unsigned int i = 0; i < rank; i++)
3737 {
3738 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3739 auto currentDimension = inputInfo.GetShape()[i];
3740 if (skipSqueeze || currentDimension != 1)
3741 {
3742 outputDims.push_back(currentDimension);
3743 }
3744 }
3745
3746 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3747
3748 armnn::TensorInfo outputInfo = inputInfo;
3749 outputInfo.SetShape(outShape);
3750
3751 armnn::ReshapeDescriptor reshapeDesc;
3752 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3753
3754 bool isSupported = false;
3755 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3756 IsReshapeSupported,
3757 data.m_Backends,
3758 isSupported,
3759 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003760 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003761 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003762
Mike Kelly46272802019-08-14 17:00:48 +01003763 if (!isSupported)
3764 {
3765 return false;
3766 }
3767
3768 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3769 assert(layer != nullptr);
3770 input.Connect(layer->GetInputSlot(0));
3771
3772 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3773}
3774
3775template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003776 typename HalOperation = typename HalPolicy::Operation,
3777 typename HalModel = typename HalPolicy::Model>
3778bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003779{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003780 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003781
3782 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3783 if (!input.IsValid())
3784 {
3785 return Fail("%s: Operation has invalid inputs", __func__);
3786 }
3787
3788 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3789 unsigned int rank = inputInfo.GetNumDimensions();
3790 if (rank > 4)
3791 {
3792 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3793 }
3794
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003795 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003796 if (!output)
3797 {
3798 return Fail("%s: Could not read output 0", __func__);
3799 }
3800
3801 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003802
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003803 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3804 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3805 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003806
3807 std::vector<int32_t> beginValues;
3808 std::vector<int32_t> endValues;
3809 std::vector<int32_t> stridesValues;
3810
3811 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003812 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003813 {
3814 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3815 {
3816 return false;
3817 }
3818
3819 if (operandValues.size() != rank)
3820 {
3821 return false;
3822 }
3823
3824 return true;
3825 };
3826
3827 if (!ValidateInputOperands(*beginOperand, beginValues)
3828 || !ValidateInputOperands(*endOperand, endValues)
3829 || !ValidateInputOperands(*stridesOperand, stridesValues))
3830 {
3831 return Fail("%s: Operation has invalid input operand", __func__);
3832 }
3833
3834 // Stride cannot have value '0'
3835 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3836 {
3837 return Fail("%s: Stride must be non-zero value.", __func__);
3838 }
3839
3840 armnn::StridedSliceDescriptor descriptor;
3841 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3842 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3843 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3844 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3845
3846 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3847 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3848 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3849 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3850 {
3851 return Fail("%s: Operation has invalid inputs", __func__);
3852 }
3853
3854 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003855 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3856 {
3857 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3858 IsStridedSliceSupported,
3859 data.m_Backends,
3860 isSupported,
3861 inputInfo,
3862 outputInfo,
3863 descriptor);
3864 };
3865
3866 if(IsDynamicTensor(outputInfo))
3867 {
3868 isSupported = AreDynamicTensorsSupported();
3869 }
3870 else
3871 {
3872 validateFunc(outputInfo, isSupported);
3873 }
3874
Mike Kelly46272802019-08-14 17:00:48 +01003875 if (!isSupported)
3876 {
3877 return false;
3878 }
3879
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003880 // Check if slice can fit in a inferred output
3881 armnn::TensorShape inputShape = inputInfo.GetShape();
3882 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3883 {
3884 int stride = descriptor.m_Stride[i];
3885 int start = descriptor.GetStartForAxis(inputShape, i);
3886 int stop = descriptor.GetStopForAxis(inputShape, i, start);
3887
3888 if (descriptor.m_ShrinkAxisMask & (1 << i))
3889 {
3890 // If the difference between the start point and the end point of the slice on an axis being shrunk
3891 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3892 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3893 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3894 {
3895 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3896 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003897
3898 if(stride < 0)
3899 {
3900 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3901 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003902 }
3903 }
3904
Mike Kelly46272802019-08-14 17:00:48 +01003905 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3906 assert(layer != nullptr);
3907 input.Connect(layer->GetInputSlot(0));
3908
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003909 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003910}
3911
3912template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003913 typename HalOperation = typename HalPolicy::Operation,
3914 typename HalModel = typename HalPolicy::Model>
3915bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003916{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003917 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003918 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003919
3920 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3921 if (!input.IsValid())
3922 {
3923 return Fail("%s: Operation has invalid inputs", __func__);
3924 }
3925
3926 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3927 unsigned int rank = inputInfo.GetNumDimensions();
3928 if (rank > 4)
3929 {
3930 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3931 }
3932
3933 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3934 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003935 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003936
3937 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003938 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003939 {
Mike Kelly46272802019-08-14 17:00:48 +01003940 for (unsigned int i = rank; i > 0; i--)
3941 {
Matthew Sloyan9b088d92020-09-14 15:12:55 +01003942 perm[rank - i] = armnn::numeric_cast<int> (i - 1);
Mike Kelly46272802019-08-14 17:00:48 +01003943 }
3944 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003945 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003946 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003947 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003948 }
3949
3950 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3951
Mike Kelly4a956582020-02-28 10:32:09 +00003952 armnn::TransposeDescriptor transposeDesc;
3953 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003954
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003955 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003956 if (!output)
3957 {
3958 return Fail("%s: Could not read output 0", __func__);
3959 }
3960
3961 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3962
3963 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003964 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3965 {
3966 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3967 IsTransposeSupported,
3968 data.m_Backends,
3969 isSupported,
3970 inputInfo,
3971 outputInfo,
3972 transposeDesc);
3973 };
3974
3975 if(IsDynamicTensor(outputInfo))
3976 {
3977 isSupported = AreDynamicTensorsSupported();
3978 }
3979 else
3980 {
3981 validateFunc(outputInfo, isSupported);
3982 }
3983
Mike Kelly46272802019-08-14 17:00:48 +01003984 if (!isSupported)
3985 {
3986 return false;
3987 }
3988
Mike Kelly4a956582020-02-28 10:32:09 +00003989 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003990 assert(layer != nullptr);
3991 input.Connect(layer->GetInputSlot(0));
3992
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003993 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003994}
3995
3996template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003997 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003998 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003999 typename HalModel = typename HalPolicy::Model>
4000bool ConvertBatchToSpaceNd(const HalOperation& operation,
4001 const HalModel& model,
4002 ConversionData& data)
4003{
Finn Williams23b87b32019-07-30 11:44:05 +01004004
4005 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4006 if (!input.IsValid())
4007 {
4008 return Fail("%s: Operation has invalid inputs", __func__);
4009 }
4010
4011 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4012 if (!output)
4013 {
4014 return Fail("%s: Could not read output 0", __func__);
4015 }
4016
4017 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004018
4019 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4020 if (!blockOperand)
4021 {
4022 return Fail("%s: Could not read input 1", __func__);
4023 }
4024
4025 // Convert the block operand to int32
4026 std::vector<int32_t> block;
4027 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4028 {
4029 return Fail("%s: Input 1 has invalid values", __func__);
4030 }
4031
4032 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4033
4034 unsigned int rank = inputInfo.GetNumDimensions();
4035 if (rank != 4)
4036 {
4037 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4038 }
4039
4040 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4041 {
4042 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4043 " greater than or equal to 1", __func__);
4044 }
4045
4046 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4047 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4048 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4049
Kevin May42477c12020-03-26 13:34:14 +00004050 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004051 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004052 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004053 }
4054 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4055 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4056
4057 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004058 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4059 {
4060 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4061 IsBatchToSpaceNdSupported,
4062 data.m_Backends,
4063 isSupported,
4064 inputInfo,
4065 outputInfo,
4066 batchToSpaceNdDesc);
4067 };
4068
4069 if(!IsDynamicTensor(outputInfo))
4070 {
4071 validateFunc(outputInfo, isSupported);
4072 }
4073 else
4074 {
4075 isSupported = AreDynamicTensorsSupported();
4076 }
4077
4078
Finn Williams23b87b32019-07-30 11:44:05 +01004079 if (!isSupported)
4080 {
4081 return false;
4082 }
4083
4084 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4085 assert(layer != nullptr);
4086 input.Connect(layer->GetInputSlot(0));
4087
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004088 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004089}
Mike Kelly0a879362019-07-29 16:56:31 +01004090
Finn Williamsd74c5052019-07-30 17:06:00 +01004091template<typename HalPolicy,
4092 typename HalOperation = typename HalPolicy::Operation,
4093 typename HalOperand = typename HalPolicy::Operand,
4094 typename HalModel = typename HalPolicy::Model>
4095bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4096{
4097 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4098 if (!input.IsValid())
4099 {
4100 return Fail("%s: Operation has invalid inputs", __func__);
4101 }
4102
4103 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4104 unsigned int rank = inputInfo.GetNumDimensions();
4105 unsigned int spatialDim = rank - 2;
4106
4107 if (rank != 4)
4108 {
4109 Fail("%s: Only inputs with rank 4 are supported", __func__);
4110 }
4111
4112 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4113 if (!output)
4114 {
4115 return Fail("%s: Could not read output 0", __func__);
4116 }
4117
4118 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004119
4120 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4121 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4122
4123 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4124 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4125 {
4126 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4127 }
4128
4129 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004130 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4131 {
4132 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4133 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004134 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4135 {
4136 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4137 }
4138
4139 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4140 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4141 {
4142 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4143 }
4144
4145 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4146 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004147 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4148 {
4149 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4150 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004151 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4152 {
4153 int paddingBeforeInput = paddings[i];
4154 int paddingAfterInput = paddings[i + 1];
4155 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4156 {
4157 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4158 }
4159
4160 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4161 }
4162
4163 armnn::SpaceToBatchNdDescriptor descriptor;
4164 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4165 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4166 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4167
Kevin May42477c12020-03-26 13:34:14 +00004168 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004169 {
4170 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4171 }
4172
4173 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004174 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4175 {
4176 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4177 IsSpaceToBatchNdSupported,
4178 data.m_Backends,
4179 isSupported,
4180 inputInfo,
4181 outputInfo,
4182 descriptor);
4183 };
4184
4185 if(IsDynamicTensor(outputInfo))
4186 {
4187 isSupported = AreDynamicTensorsSupported();
4188 }
4189 else
4190 {
4191 validateFunc(outputInfo, isSupported);
4192 }
4193
Finn Williamsd74c5052019-07-30 17:06:00 +01004194 if (!isSupported)
4195 {
4196 return false;
4197 }
4198
4199 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4200 assert(layer != nullptr);
4201 input.Connect(layer->GetInputSlot(0));
4202
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004203 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004204}
4205
saoste01b8471482018-10-10 09:44:51 +01004206} // namespace armnn_driver