blob: b9c4d411ccfea3937a239895863143e33389d380 [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 });
arovir01b0717b52018-09-05 17:03:25 +0100492const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
493
494// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000495const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
496const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100497
498template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000499armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
500 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100501{
502 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000503 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
arovir01b0717b52018-09-05 17:03:25 +0100504
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100505 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100506
507 // Connect input to swizzle layer
508 input.Connect(layer->GetInputSlot(0));
509
510 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000511 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100512 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
513
514 return *layer;
515}
516
arovir01b0717b52018-09-05 17:03:25 +0100517bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
518 const armnn::TensorShape & outputShape,
519 uint32_t concatDim)
520{
521 // Validate the output shape is correct given the input shapes (which have just been validated)
522 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
523 if (outputShape.GetNumDimensions() != numDimensions)
524 {
525 return Fail("%s: Output shape has wrong number of dimensions", __func__);
526 }
527
528 unsigned int outputSizeAlongConcatenatedDimension = 0;
529 for (unsigned int i = 0; i < inputShapes.size(); i++)
530 {
531 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
532 }
533
534 for (unsigned int i = 0; i < numDimensions; ++i)
535 {
536 if (i == concatDim)
537 {
538 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
539 {
540 return Fail(
541 "%s: Invalid output shape for dimension %d (%d != %d)",
542 __func__,
543 i,
544 outputShape[i],
545 outputSizeAlongConcatenatedDimension);
546 }
547 }
548 else
549 {
550 if (outputShape[i] != inputShapes[0][i])
551 {
552 return Fail("%s: Invalid output shape", __func__);
553 }
554 }
555 }
556
557 return true;
558}
559
560bool RequiresReshape(armnn::TensorShape & inputShape)
561{
562 return inputShape.GetNumDimensions() < 3;
563}
564
arovir01b0717b52018-09-05 17:03:25 +0100565void SwizzleInputs(armnn::INetwork& network,
566 std::vector<LayerInputHandle>& inputs,
567 std::vector<armnn::TensorShape>& inputShapes,
568 const armnn::PermutationVector& mapping)
569{
570 if (!mapping.IsEqual(IdentityPermutation4D))
571 {
572 size_t nInputs = inputs.size();
573 for (size_t i=0; i<nInputs; ++i)
574 {
575 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000576 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100577 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
578 auto& outputInfo = outputSlot.GetTensorInfo();
579 // replace inputs with the swizzled ones
580 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
581 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
582 }
583 }
584}
585
Teresa Charlin185f5882020-04-06 21:59:18 +0100586bool TransposeInputTensors(ConversionData& data,
587 std::vector<LayerInputHandle>& inputs,
588 std::vector<armnn::TensorShape>& inputShapes,
589 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000590{
591 if (!mapping.IsEqual(IdentityPermutation4D))
592 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100593 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000594 size_t nInputs = inputs.size();
595 for (size_t i=0; i<nInputs; ++i)
596 {
597 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000598 armnn::TransposeDescriptor transposeDesc;
599 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100600 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000601
602 bool isSupported = false;
603 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000604 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000605 data.m_Backends,
606 isSupported,
607 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100608 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000609 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000610 if (!isSupported)
611 {
612 return false;
613 }
614
615 }
616 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
617 }
618 return true;
619}
620
621
narpra01f176d5a2018-11-18 20:17:48 +0000622bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
623 int32_t & concatDimension,
624 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100625{
narpra01f176d5a2018-11-18 20:17:48 +0000626 bool needPermute = false;
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100627 ARMNN_ASSERT(numberOfDimensions >= 3);
arovir01b0717b52018-09-05 17:03:25 +0100628
629 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000630 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
631 // or along dimension 0 or 2 for a 3-D tensor.
632 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100633 {
narpra01f176d5a2018-11-18 20:17:48 +0000634 concatDimension = 1;
635 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
636 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100637 }
narpra01f176d5a2018-11-18 20:17:48 +0000638 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100639 {
narpra01f176d5a2018-11-18 20:17:48 +0000640 concatDimension = 0;
641 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
642 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100643 }
narpra01f176d5a2018-11-18 20:17:48 +0000644 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100645}
646
647} // anonymous namespace
648
649namespace armnn_driver
650{
651
652//// Creates an ArmNN activation layer and connects it to the given layer, if the
653//// passed in AndroidNN activation function requires so.
654//// @return The end layer of the sequence of layers built for the given AndroidNN
655//// activation function or nullptr if an error occurred (e.g. unsupported activation).
656//// Note that the end layer matches the input layer if no activation is required
657//// (the sequence of layers has length 1).
658armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
659 ActivationFn activation,
660 armnn::IConnectableLayer* prevLayer,
661 ConversionData& data);
662
663} // namespace armnn_driver
664
665///
666/// Utility templates
667///
668
669namespace armnn_driver
670{
671
672using namespace android::nn;
673
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100674template<typename HalPolicy,
675 typename HalOperand = typename HalPolicy::Operand,
676 typename HalOperation = typename HalPolicy::Operation,
677 typename HalModel = typename HalPolicy::Model>
678const HalOperand* GetInputOperand(const HalOperation& operation,
679 uint32_t inputIndex,
680 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100681 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100682{
683 if (inputIndex >= operation.inputs.size())
684 {
saoste01b8471482018-10-10 09:44:51 +0100685 if (failOnIndexOutOfBounds)
686 {
687 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
688 }
arovir01b0717b52018-09-05 17:03:25 +0100689 return nullptr;
690 }
691
Kevin May42477c12020-03-26 13:34:14 +0000692 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100693 ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
Kevin May42477c12020-03-26 13:34:14 +0000694 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100695}
696
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100697template<typename HalPolicy,
698 typename HalOperand = typename HalPolicy::Operand,
699 typename HalOperation = typename HalPolicy::Operation,
700 typename HalModel = typename HalPolicy::Model>
701const HalOperand* GetOutputOperand(const HalOperation& operation,
702 uint32_t outputIndex,
703 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100704{
705 if (outputIndex >= operation.outputs.size())
706 {
707 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
708 return nullptr;
709 }
710
711 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100712 ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
arovir01b0717b52018-09-05 17:03:25 +0100713
Kevin May42477c12020-03-26 13:34:14 +0000714 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100715}
716
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100717template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100718 typename HalOperand = typename HalPolicy::Operand,
719 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100720const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100721 const HalModel& model,
722 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000723 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100724{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100725 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100726
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100727 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100728 switch (operand.lifetime)
729 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100730 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100731 {
732 // Constant found in model.operandValues
733 valueStart = &model.operandValues[operand.location.offset];
734 break;
735 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100736 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100737 {
738 // Constant specified via a Memory object
739 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
740 break;
741 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100742 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000743 {
744 // An optional input tensor with no values is not an error so should not register as a fail
745 if (optional)
746 {
747 valueStart = nullptr;
748 break;
749 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100750 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000751 }
arovir01b0717b52018-09-05 17:03:25 +0100752 default:
753 {
754 // Unsupported/invalid (e.g. can't get value of an input to the model)
755 Fail("%s: unsupported/invalid operand lifetime: %s",
756 __func__, toString(operand.lifetime).c_str());
757 valueStart = nullptr;
758 }
759 }
760
761 return valueStart;
762}
763
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100764template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100765 typename HalOperation = typename HalPolicy::Operation,
766 typename HalModel = typename HalPolicy::Model,
767 typename HalOperandType = typename HalPolicy::OperandType>
768bool GetOperandType(const HalOperation& operation,
769 uint32_t inputIndex,
770 const HalModel& model,
771 HalOperandType& type)
772{
773 using HalOperand = typename HalPolicy::Operand;
774
775 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
776 if (!operand)
777 {
778 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
779 }
780
781 type = operand->type;
782 return true;
783}
784
785template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000786 typename HalOperand = typename HalPolicy::Operand>
787bool IsOperandConstant(const HalOperand& operand)
788{
789 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
790
791 HalOperandLifeTime lifetime = operand.lifetime;
792
793 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
794 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
795 lifetime == HalOperandLifeTime::NO_VALUE;
796}
797
798template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100799 typename HalOperand = typename HalPolicy::Operand,
800 typename HalModel = typename HalPolicy::Model>
801ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
802 const HalModel& model,
803 const ConversionData& data,
804 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
805 const armnn::TensorShape* overrideTensorShape = nullptr,
806 bool optional = false)
807{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100808 if (!IsOperandTypeSupportedForTensors(operand.type))
809 {
810 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
811 return ConstTensorPin();
812 }
813
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000814 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100815 {
816 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
817 return ConstTensorPin();
818 }
819
820 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
821 if (!valueStart)
822 {
823 if (optional)
824 {
825 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
826 return ConstTensorPin(true);
827 }
828 // mandatory tensor with no values
829 Fail("%s: failed to get operand address", __func__);
830 return ConstTensorPin();
831 }
832
833 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000834 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
835 if (tensorInfo.HasPerAxisQuantization())
836 {
837 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
838 }
839
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100840 if (overrideTensorShape != nullptr)
841 {
842 tensorInfo.SetShape(*overrideTensorShape);
843 }
844 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
845}
846
847template<typename HalPolicy,
848 typename HalOperation = typename HalPolicy::Operation,
849 typename HalModel = typename HalPolicy::Model>
850ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
851 uint32_t inputIndex,
852 const HalModel& model,
853 const ConversionData& data,
854 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
855 const armnn::TensorShape* overrideTensorShape = nullptr,
856 bool optional = false)
857{
858 using HalOperand = typename HalPolicy::Operand;
859
860 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
861 if (!operand)
862 {
863 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
864 return ConstTensorPin();
865 }
866 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
867 model,
868 data,
869 dimensionMappings,
870 overrideTensorShape,
871 optional);
872}
873
874template<typename HalPolicy,
875 typename OutputType,
876 typename HalOperandType = typename HalPolicy::OperandType,
877 typename HalOperation = typename HalPolicy::Operation,
878 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100879bool GetInputScalar(const HalOperation& operation,
880 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100881 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100882 OutputType& outValue,
883 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100884 const ConversionData& data,
885 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100886{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100887 using HalOperand = typename HalPolicy::Operand;
888
889 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100890 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100891 {
892 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
893 }
894
Sadik Armagan813f2302020-05-19 14:10:30 +0100895 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100896 {
897 return Fail("%s: unexpected operand type: %s (should be %s)",
898 __func__, toString(operand->type).c_str(), toString(type).c_str());
899 }
900
Sadik Armagan813f2302020-05-19 14:10:30 +0100901 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100902 {
903 return Fail("%s: incorrect operand location length: %i (should be %i)",
904 __func__, operand->location.length, sizeof(OutputType));
905 }
906
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100907 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100908 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100909 {
910 return Fail("%s: failed to get address for operand", __func__);
911 }
912
Sadik Armagan813f2302020-05-19 14:10:30 +0100913 if(!optional)
914 {
915 outValue = *(static_cast<const OutputType*>(valueAddress));
916 }
917
arovir01b0717b52018-09-05 17:03:25 +0100918 return true;
919}
920
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100921template<typename HalPolicy,
922 typename HalOperation = typename HalPolicy::Operation,
923 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100924bool GetInputInt32(const HalOperation& operation,
925 uint32_t inputIndex,
926 int32_t& outValue,
927 const HalModel& model,
928 const ConversionData& data)
929{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100930 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100931}
932
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100933template<typename HalPolicy,
934 typename HalOperation = typename HalPolicy::Operation,
935 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100936bool GetInputFloat32(const HalOperation& operation,
937 uint32_t inputIndex,
938 float& outValue,
939 const HalModel& model,
940 const ConversionData& data)
941{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100942 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100943}
944
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100945template<typename HalPolicy,
946 typename HalOperation = typename HalPolicy::Operation,
947 typename HalOperandType = typename HalPolicy::OperandType,
948 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100949bool GetInputActivationFunctionImpl(const HalOperation& operation,
950 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100951 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100952 ActivationFn& outActivationFunction,
953 const HalModel& model,
954 const ConversionData& data)
955{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100956 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100957 {
958 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
959 __func__,
960 toString(type).c_str(),
961 toString(OperandType::INT32).c_str(),
962 toString(OperandType::TENSOR_INT32).c_str());
963 }
964
965 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100966 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100967 {
968 return Fail("%s: failed to get activation input value", __func__);
969 }
970 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
971 return true;
972}
973
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100974template<typename HalPolicy,
975 typename HalOperation = typename HalPolicy::Operation,
976 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100977bool GetInputActivationFunction(const HalOperation& operation,
978 uint32_t inputIndex,
979 ActivationFn& outActivationFunction,
980 const HalModel& model,
981 const ConversionData& data)
982{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100983 return GetInputActivationFunctionImpl<HalPolicy>(operation,
984 inputIndex,
985 HalPolicy::OperandType::INT32,
986 outActivationFunction,
987 model,
988 data);
arovir01b0717b52018-09-05 17:03:25 +0100989}
990
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100991template<typename HalPolicy,
992 typename HalOperation = typename HalPolicy::Operation,
993 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100994bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
995 uint32_t inputIndex,
996 ActivationFn& outActivationFunction,
997 const HalModel& model,
998 const ConversionData& data)
999{
1000 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001001 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1002 inputIndex,
1003 HalPolicy::OperandType::INT32,
1004 outActivationFunction,
1005 model,
1006 data);
arovir01b0717b52018-09-05 17:03:25 +01001007}
1008
1009
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001010template<typename HalPolicy,
1011 typename HalOperation = typename HalPolicy::Operation,
1012 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001013bool GetOptionalInputActivation(const HalOperation& operation,
1014 uint32_t inputIndex,
1015 ActivationFn& activationFunction,
1016 const HalModel& model,
1017 const ConversionData& data)
1018{
1019 if (operation.inputs.size() <= inputIndex)
1020 {
1021 activationFunction = ActivationFn::kActivationNone;
1022 }
1023 else
1024 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001025 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001026 {
1027 return Fail("%s: Operation has invalid inputs", __func__);
1028 }
1029 }
1030 return true;
1031}
1032
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001033template<typename HalPolicy,
1034 typename ConvolutionDescriptor,
1035 typename HalOperation = typename HalPolicy::Operation,
1036 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001037bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1038 uint32_t dilationXIndex,
1039 ConvolutionDescriptor& descriptor,
1040 const HalModel& model,
1041 const ConversionData& data)
1042{
1043 bool success = true;
1044 if (operation.inputs.size() >= dilationXIndex + 2)
1045 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001046 success &= GetInputScalar<HalPolicy>(operation,
1047 dilationXIndex,
1048 HalPolicy::OperandType::INT32,
1049 descriptor.m_DilationX,
1050 model,
1051 data);
1052 success &= GetInputScalar<HalPolicy>(operation,
1053 dilationXIndex + 1,
1054 HalPolicy::OperandType::INT32,
1055 descriptor.m_DilationY,
1056 model,
1057 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001058 }
1059
1060 return success;
1061}
1062
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001063template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001064 typename HalOperation = typename HalPolicy::Operation,
1065 typename HalModel = typename HalPolicy::Model>
1066bool GetOptionalBool(const HalOperation& operation,
1067 uint32_t inputIndex,
1068 const HalModel& model,
1069 const ConversionData& data)
1070{
1071 using HalOperand = typename HalPolicy::Operand;
1072
1073 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1074 if (!operand)
1075 {
1076 return false;
1077 }
1078
1079 if (!IsBool(*operand))
1080 {
1081 return false;
1082 }
1083
1084 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1085 if (!valueAddress)
1086 {
1087 return false;
1088 }
1089
1090 if (*(static_cast<const bool*>(valueAddress)))
1091 {
1092 return true;
1093 }
1094 else
1095 {
1096 return false;
1097 }
1098}
1099
1100template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001101 typename HalOperand = typename HalPolicy::Operand,
1102 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001103bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001104 std::vector<int32_t>& outValues,
1105 const HalModel& model,
1106 const ConversionData& data)
1107{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001108 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001109 {
1110 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1111 }
1112
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001113 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001114 if (!startAddress)
1115 {
1116 return Fail("%s: failed to get operand address", __func__, operand.type);
1117 }
1118
1119 // Check number of bytes is sensible
1120 const uint32_t numBytes = operand.location.length;
1121 if (numBytes % sizeof(int32_t) != 0)
1122 {
1123 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1124 __func__, numBytes, sizeof(int32_t));
1125 }
1126
1127 outValues.resize(numBytes / sizeof(int32_t));
1128 memcpy(outValues.data(), startAddress, numBytes);
1129 return true;
1130}
1131
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001132template<typename HalPolicy,
1133 typename HalOperation = typename HalPolicy::Operation,
1134 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001135bool GetInputPaddingScheme(const HalOperation& operation,
1136 uint32_t inputIndex,
1137 PaddingScheme& outPaddingScheme,
1138 const HalModel& model,
1139 const ConversionData& data)
1140{
1141 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001142 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001143 {
1144 return Fail("%s: failed to get padding scheme input value", __func__);
1145 }
1146
1147 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1148 return true;
1149}
1150
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001151template<typename HalPolicy,
1152 typename HalOperation = typename HalPolicy::Operation,
1153 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001154LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1155 uint32_t inputIndex,
1156 const HalModel& model,
1157 ConversionData& data)
1158{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001159 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001160 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001161 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1162
1163 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001164 if (!operand)
1165 {
1166 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1167 return LayerInputHandle();
1168 }
1169
1170 if (!IsOperandTypeSupportedForTensors(operand->type))
1171 {
1172 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1173 return LayerInputHandle();
1174 }
1175
Sadik Armagan44bcc022019-06-18 17:21:36 +01001176 try
arovir01b0717b52018-09-05 17:03:25 +01001177 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001178 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001179 if (IsDynamicTensor(operandTensorInfo))
1180 {
1181 Fail("%s: dynamic input tensors are not supported", __func__);
1182 return LayerInputHandle();
1183 }
arovir01b0717b52018-09-05 17:03:25 +01001184
Sadik Armagan44bcc022019-06-18 17:21:36 +01001185 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001186 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001187 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001188 {
1189 // NOTE: We must check whether we can support the input tensor on at least one
1190 // of the provided backends; otherwise we cannot convert the operation
1191 bool isInputSupported = false;
1192 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1193 IsInputSupported,
1194 data.m_Backends,
1195 isInputSupported,
1196 operandTensorInfo);
1197
1198 if (!isInputSupported)
1199 {
1200 Fail("%s: unsupported input tensor", __func__);
1201 return LayerInputHandle();
1202 }
1203
1204 BOOST_FALLTHROUGH; // intentional fallthrough
1205 }
1206 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001207 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001208 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001209 // The tensor is either an operand internal to the model, or a model input.
1210 // It can be associated with an ArmNN output slot for an existing layer.
1211
1212 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1213 const uint32_t operandIndex = operation.inputs[inputIndex];
1214 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001215 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001216 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001217 case HalOperandLifeTime::CONSTANT_REFERENCE:
1218 {
1219 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1220 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1221 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001222 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001223 bool isSupported = false;
1224 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1225 IsConstantSupported,
1226 data.m_Backends,
1227 isSupported,
1228 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001229 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001230 {
1231 return LayerInputHandle();
1232 }
1233
1234 armnn::IConnectableLayer* constantLayer =
1235 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1236 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1237 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1238
1239 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1240 }
1241 else
1242 {
1243 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001244 return LayerInputHandle();
1245 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001246 break;
arovir01b0717b52018-09-05 17:03:25 +01001247 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001248 default:
arovir01b0717b52018-09-05 17:03:25 +01001249 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001250 // Unsupported lifetime for an input tensor
1251 Fail("%s: unsupported lifetime for input tensor: %s",
1252 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001253 return LayerInputHandle();
1254 }
arovir01b0717b52018-09-05 17:03:25 +01001255 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001256 }
1257 catch (UnsupportedOperand<HalOperandType>& e)
1258 {
1259 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1260 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001261 }
1262}
1263
Kevin May42477c12020-03-26 13:34:14 +00001264
1265#ifdef ARMNN_ANDROID_NN_V1_3
1266template<typename HalPolicy>
1267LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1268 uint32_t inputIndex,
1269 const::android::hardware::neuralnetworks::V1_3::Model& model,
1270 ConversionData& data)
1271{
1272 using HalOperand = typename HalPolicy::Operand;
1273 using HalOperandType = typename HalPolicy::OperandType;
1274 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1275
1276 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1277 if (!operand)
1278 {
1279 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1280 return LayerInputHandle();
1281 }
1282
1283 if (!IsOperandTypeSupportedForTensors(operand->type))
1284 {
1285 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1286 return LayerInputHandle();
1287 }
1288
1289 try
1290 {
1291 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Finn Williams9a044412020-08-17 19:08:35 +01001292
Kevin May42477c12020-03-26 13:34:14 +00001293 if (IsDynamicTensor(operandTensorInfo))
1294 {
Finn Williams291a16b2020-08-19 22:54:00 +01001295 data.m_DynamicInputsEncountered = true;
1296
Finn Williams9a044412020-08-17 19:08:35 +01001297 const uint32_t operandIndex = operation.inputs[inputIndex];
1298
1299 // Check if the dynamic input tensors have been inferred by one of the previous layers
1300 // If not we can't support them
Finn Williams291a16b2020-08-19 22:54:00 +01001301 if (data.m_OutputSlotForOperand.size() >= operandIndex && data.m_OutputSlotForOperand[operandIndex])
Finn Williams9a044412020-08-17 19:08:35 +01001302 {
1303 operandTensorInfo = data.m_OutputSlotForOperand[operandIndex]->GetTensorInfo();
1304 }
1305 else
1306 {
1307 Fail("%s: Type 2 dynamic input tensors are not supported", __func__);
1308 return LayerInputHandle();
1309 }
Kevin May42477c12020-03-26 13:34:14 +00001310 }
1311
1312 switch (operand->lifetime)
1313 {
1314 case HalOperandLifeTime::SUBGRAPH_INPUT:
1315 {
1316 // NOTE: We must check whether we can support the input tensor on at least one
1317 // of the provided backends; otherwise we cannot convert the operation
1318 bool isInputSupported = false;
1319 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1320 IsInputSupported,
1321 data.m_Backends,
1322 isInputSupported,
1323 operandTensorInfo);
1324
1325 if (!isInputSupported)
1326 {
1327 Fail("%s: unsupported input tensor", __func__);
1328 return LayerInputHandle();
1329 }
1330
1331 BOOST_FALLTHROUGH; // intentional fallthrough
1332 }
1333 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1334 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1335 {
1336 // The tensor is either an operand internal to the model, or a model input.
1337 // It can be associated with an ArmNN output slot for an existing layer.
1338
1339 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1340 const uint32_t operandIndex = operation.inputs[inputIndex];
1341 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1342 }
1343 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1344 case HalOperandLifeTime::CONSTANT_REFERENCE:
1345 {
1346 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1347 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1348 if (tensorPin.IsValid())
1349 {
1350 bool isSupported = false;
1351 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1352 IsConstantSupported,
1353 data.m_Backends,
1354 isSupported,
1355 tensorPin.GetConstTensor().GetInfo());
1356 if (!isSupported)
1357 {
1358 return LayerInputHandle();
1359 }
1360
1361 armnn::IConnectableLayer* constantLayer =
1362 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1363 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1364 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1365
1366 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1367 }
1368 else
1369 {
1370 Fail("%s: invalid operand tensor", __func__);
1371 return LayerInputHandle();
1372 }
1373 break;
1374 }
1375 default:
1376 {
1377 // Unsupported lifetime for an input tensor
1378 Fail("%s: unsupported lifetime for input tensor: %s",
1379 __func__, toString(operand->lifetime).c_str());
1380 return LayerInputHandle();
1381 }
1382 }
1383 }
1384 catch (UnsupportedOperand<HalOperandType>& e)
1385 {
1386 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1387 return LayerInputHandle();
1388 }
1389}
1390#endif
1391
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001392template<typename HalPolicy,
1393 typename HalOperation = typename HalPolicy::Operation,
1394 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001395bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1396 uint32_t operationOutputIndex,
1397 armnn::IConnectableLayer& layer,
1398 uint32_t layerOutputIndex,
1399 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001400 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001401 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001402 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001403 const ActivationFn& activationFunction = ActivationFn::kActivationNone,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001404 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001405{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001406 using HalOperand = typename HalPolicy::Operand;
1407
1408 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001409 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1410 {
1411 return false;
1412 }
1413
1414 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001415 if (overrideOutputInfo == nullptr)
1416 {
1417 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1418 }
1419 else
1420 {
1421 outputSlot.SetTensorInfo(*overrideOutputInfo);
1422 }
1423
Finn Williamsa4983ce2020-07-23 12:55:12 +01001424 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001425 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001426 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001427 // Type one dynamic tensors require the previous layer's output shape for inference
1428 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1429 {
1430 if(!layer.GetInputSlot(inputSlotIndex).GetConnection())
1431 {
1432 return false;
1433 }
1434 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001435 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001436 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001437 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001438 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1439
Sadik Armagandbda4b72020-09-03 11:33:07 +01001440 if(!isSupported)
1441 {
1442 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1443 {
1444 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1445 }
1446 return false;
1447 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001448 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001449
Finn Williamsa4983ce2020-07-23 12:55:12 +01001450 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
Kevin Mayfcf2a152020-09-08 16:06:32 +01001451
1452 if (activationFunction != ActivationFn::kActivationNone)
1453 {
1454 const armnn::TensorInfo& activationOutputInfo = outputSlot.GetTensorInfo();
1455 armnn::IConnectableLayer* const endLayer = ProcessActivation(activationOutputInfo, activationFunction,
1456 &layer, data);
1457
1458 if (!endLayer)
1459 {
1460 return Fail("%s: ProcessActivation failed", __func__);
1461 }
1462
1463 armnn::IOutputSlot& activationOutputSlot = endLayer->GetOutputSlot(layerOutputIndex);
1464 data.m_OutputSlotForOperand[operandIndex] = &activationOutputSlot;
1465 }
1466 else
1467 {
1468 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1469 }
Finn Williamsa4983ce2020-07-23 12:55:12 +01001470
Mike Kellyb5fdf382019-06-11 16:35:25 +01001471 return true;
1472}
1473
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001474template<typename HalPolicy,
1475 typename HalOperation = typename HalPolicy::Operation,
1476 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001477armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1478 uint32_t inputIndex,
1479 const HalModel& model,
1480 ConversionData& data)
1481{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001482 using HalOperand = typename HalPolicy::Operand;
1483
1484 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001485 if (!operand)
1486 {
1487 return armnn::DataLayout::NHWC;
1488 }
1489
1490 if (!IsBool(*operand))
1491 {
1492 return armnn::DataLayout::NHWC;
1493 }
1494
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001495 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001496 if (!valueAddress)
1497 {
1498 return armnn::DataLayout::NHWC;
1499 }
1500
1501 if (*(static_cast<const bool*>(valueAddress)))
1502 {
1503 return armnn::DataLayout::NCHW;
1504 }
1505 else
1506 {
1507 return armnn::DataLayout::NHWC;
1508 }
1509}
1510
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001511template<typename HalPolicy,
1512 typename HalOperation = typename HalPolicy::Operation,
1513 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001514bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1515 uint32_t outputIndex,
1516 armnn::IConnectableLayer& layer,
1517 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001518 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001519 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001520 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
1521 const ActivationFn& activationFunction = ActivationFn::kActivationNone)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001522{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001523 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1524 outputIndex,
1525 layer,
1526 outputIndex,
1527 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001528 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001529 overrideOutputInfo,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001530 validateFunc,
1531 activationFunction);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001532}
1533
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001534template<typename HalPolicy,
1535 typename HalOperation = typename HalPolicy::Operation,
1536 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001537bool ConvertToActivation(const HalOperation& operation,
1538 const char* operationName,
1539 const armnn::ActivationDescriptor& activationDesc,
1540 const HalModel& model,
1541 ConversionData& data)
1542{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001543 using HalOperand = typename HalPolicy::Operand;
1544
1545 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001546 if (!input.IsValid())
1547 {
1548 return Fail("%s: Input 0 is invalid", operationName);
1549 }
1550
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001551 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001552 if (!outputOperand)
1553 {
1554 return false;
1555 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001556
1557 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001558
1559 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001560
1561 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1562 {
1563 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1564 IsActivationSupported,
1565 data.m_Backends,
1566 isSupported,
1567 input.GetTensorInfo(),
1568 outInfo,
1569 activationDesc);
1570 };
1571
1572 if(IsDynamicTensor(outInfo))
1573 {
1574 isSupported = AreDynamicTensorsSupported();
1575 }
1576 else
1577 {
1578 validateFunc(outInfo, isSupported);
1579 }
1580
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001581 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001582 {
1583 return false;
1584 }
1585
1586 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001587 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001588 input.Connect(layer->GetInputSlot(0));
1589
Finn Williamsa4983ce2020-07-23 12:55:12 +01001590 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001591}
1592
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001593template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001594 typename HalOperation = typename HalPolicy::Operation,
1595 typename HalModel = typename HalPolicy::Model>
1596bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1597{
1598 armnn::ActivationDescriptor desc;
1599 desc.m_Function = armnn::ActivationFunction::ReLu;
1600
1601 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1602}
1603
1604template<typename HalPolicy,
1605 typename HalOperation = typename HalPolicy::Operation,
1606 typename HalModel = typename HalPolicy::Model>
1607bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1608{
1609 armnn::ActivationDescriptor desc;
1610 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1611 desc.m_A = 1.0f;
1612 desc.m_B = -1.0f;
1613
1614 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1615}
1616
1617template<typename HalPolicy,
1618 typename HalOperation = typename HalPolicy::Operation,
1619 typename HalModel = typename HalPolicy::Model>
1620bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1621{
1622 armnn::ActivationDescriptor desc;
1623 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1624 desc.m_A = 6.0f;
1625
1626 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1627}
1628
1629template<typename HalPolicy,
1630 typename HalOperation = typename HalPolicy::Operation,
1631 typename HalModel = typename HalPolicy::Model>
1632bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1633{
1634 armnn::ActivationDescriptor desc;
1635 desc.m_Function = armnn::ActivationFunction::TanH;
1636 desc.m_A = 1.0f; // android nn does not support tanH parameters
1637 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1638
1639 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1640}
1641
1642template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001643 typename HalOperation = typename HalPolicy::Operation,
1644 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001645bool ConvertPaddings(const HalOperation& operation,
1646 const HalModel& model,
1647 ConversionData& data,
1648 unsigned int rank,
1649 armnn::PadDescriptor& padDescriptor)
1650{
1651 using HalOperand = typename HalPolicy::Operand;
1652
1653 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1654 if (!paddingsOperand)
1655 {
1656 return Fail("%s: Could not read paddings operand", __func__);
1657 }
1658
1659 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1660 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1661 {
1662 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1663 }
1664
1665 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001666 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1667 {
1668 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1669 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001670
1671 // add padding for each dimension of input tensor.
1672 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1673 {
1674 int paddingBeforeInput = paddings[i];
1675 int paddingAfterInput = paddings[i + 1];
1676
1677 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1678 {
1679 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1680 }
1681
1682 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1683 }
1684
1685 return true;
1686}
1687
1688template<typename HalPolicy,
1689 typename HalOperation = typename HalPolicy::Operation,
1690 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001691bool ConvertPooling2d(const HalOperation& operation,
1692 const char* operationName,
1693 armnn::PoolingAlgorithm poolType,
1694 const HalModel& model,
1695 ConversionData& data)
1696{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001697 using HalOperand = typename HalPolicy::Operand;
1698 using HalOperandType = typename HalPolicy::OperandType;
1699
1700 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001701 if (!input.IsValid())
1702 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001703 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001704 }
1705
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001706 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001707 if (!output)
1708 {
1709 return Fail("%s: Could not read output 0", __func__);
1710 }
1711
1712 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1713 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1714
arovir01b0717b52018-09-05 17:03:25 +01001715 armnn::Pooling2dDescriptor desc;
1716 desc.m_PoolType = poolType;
1717 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001718 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001719
1720 ActivationFn activation;
1721
Sadik Armagan15d63e22019-07-26 16:59:35 +01001722 auto inputSize = operation.inputs.size();
1723
1724 if (inputSize >= 10)
1725 {
1726 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1727 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1728 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1729 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1730 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1731 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1732 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1733 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1734 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1735 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1736 {
1737 return Fail("%s: Operation has invalid inputs", operationName);
1738 }
1739
Kevin May42477c12020-03-26 13:34:14 +00001740 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001741 {
1742 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1743 }
1744 }
1745 else
arovir01b0717b52018-09-05 17:03:25 +01001746 {
1747 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1748 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001749 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1750 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1751 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1752 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1753 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1754 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001755 {
1756 return Fail("%s: Operation has invalid inputs", operationName);
1757 }
1758
Kevin May42477c12020-03-26 13:34:14 +00001759 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001760 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001761 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001762 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001763
1764 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1765 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1766 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1767
1768 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1769 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001770 }
1771
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001772 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001773
1774 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1775 {
1776 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1777 IsPooling2dSupported,
1778 data.m_Backends,
1779 isSupported,
1780 inputInfo,
1781 outputInfo,
1782 desc);
1783
1784 };
1785
1786 if(IsDynamicTensor(outputInfo))
1787 {
1788 isSupported = AreDynamicTensorsSupported();
1789 }
1790 else
1791 {
1792 validateFunc(outputInfo, isSupported);
1793 }
1794
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001795 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001796 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001797 return false;
arovir01b0717b52018-09-05 17:03:25 +01001798 }
arovir01b0717b52018-09-05 17:03:25 +01001799
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001800 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1801 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001802 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001803 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001804 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001805
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001806 input.Connect(pooling2dLayer->GetInputSlot(0));
1807
Finn Williamsa4983ce2020-07-23 12:55:12 +01001808 if (!isSupported)
1809 {
1810 return false;
1811 }
1812
Kevin Mayfcf2a152020-09-08 16:06:32 +01001813 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *pooling2dLayer, model,
1814 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001815}
1816
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001817template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001818 typename HalOperation = typename HalPolicy::Operation,
1819 typename HalModel = typename HalPolicy::Model>
1820bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001821{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001822 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001823
1824 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1825 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1826
1827 if (!input0.IsValid() || !input1.IsValid())
1828 {
1829 return Fail("%s: Operation has invalid inputs", __func__);
1830 }
1831
1832 // The FuseActivation parameter is always the input index 2
1833 // and it should be optional
1834 ActivationFn activationFunction;
1835 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1836 {
1837 return Fail("%s: Operation has invalid inputs", __func__);
1838 }
1839
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001840 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001841 if (!outputOperand)
1842 {
1843 return false;
1844 }
1845
1846 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1847 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1848
1849 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001850
1851 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001852 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1853 {
1854 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1855 IsAdditionSupported,
1856 data.m_Backends,
1857 isSupported,
1858 inputInfo0,
1859 inputInfo1,
1860 outputInfo);
1861 };
1862
1863 if(!IsDynamicTensor(outputInfo))
1864 {
1865 validateFunc(outputInfo, isSupported);
1866 }
1867 else
1868 {
1869 isSupported = AreDynamicTensorsSupported();
1870 }
1871
Mike Kelly46272802019-08-14 17:00:48 +01001872 if (!isSupported)
1873 {
1874 return false;
1875 }
1876
1877 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01001878
Kevin Mayfcf2a152020-09-08 16:06:32 +01001879 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1880 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01001881 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01001882 return false;
1883 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01001884
Kevin Mayfcf2a152020-09-08 16:06:32 +01001885 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
1886 data, nullptr, validateFunc, activationFunction);
1887
Mike Kelly46272802019-08-14 17:00:48 +01001888}
1889
1890template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001891 typename HalOperation = typename HalPolicy::Operation,
1892 typename HalModel = typename HalPolicy::Model>
1893bool ConvertArgMinMax(const HalOperation& operation,
1894 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001895 ConversionData& data,
1896 armnn::ArgMinMaxFunction argMinMaxFunction)
1897{
1898 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1899
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001900 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001901 using HalOperandType = typename HalPolicy::OperandType;
1902
1903 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1904
1905 if (!input0.IsValid())
1906 {
1907 return Fail("%s: Operation has invalid inputs", __func__);
1908 }
1909
1910 int32_t axis;
1911 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1912 {
1913 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1914 }
1915
1916 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1917 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1918
1919 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1920 {
1921 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1922 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1923 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1924 return Fail("%s: Axis must be in range [-n, n)", __func__);
1925 }
1926
1927 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1928 if (!output)
1929 {
1930 return Fail("%s: Could not read output 0", __func__);
1931 }
1932
1933 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1934
1935 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001936
1937 armnn::ArgMinMaxDescriptor descriptor;
1938 descriptor.m_Function = argMinMaxFunction;
1939 descriptor.m_Axis = axis;
1940
1941 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001942
1943 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1944 {
1945 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1946 IsArgMinMaxSupported,
1947 data.m_Backends,
1948 isSupported,
1949 inputInfo0,
1950 outputInfo,
1951 descriptor);
1952 };
1953
1954 if(IsDynamicTensor(outputInfo))
1955 {
1956 isSupported = AreDynamicTensorsSupported();
1957 }
1958 else
1959 {
1960 validateFunc(outputInfo, isSupported);
1961 }
1962
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001963 if (!isSupported)
1964 {
1965 return false;
1966 }
1967
1968 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1969 assert(layer != nullptr);
1970
1971 input0.Connect(layer->GetInputSlot(0));
1972
Finn Williamsa4983ce2020-07-23 12:55:12 +01001973 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001974}
1975
1976template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001977 typename HalOperation = typename HalPolicy::Operation,
1978 typename HalModel = typename HalPolicy::Model>
1979bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001980{
Keith Davis6e4081f2020-09-03 13:17:21 +01001981 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001982 using HalOperandType = typename HalPolicy::OperandType;
1983
1984 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1985 if (operation.inputs.size() <= 1)
1986 {
1987 return Fail("%s: Operation has insufficient arguments", __func__);
1988 }
1989
1990 // Get inputs and outputs
1991 const std::size_t numInputTensors = operation.inputs.size() - 1;
1992
1993 int32_t concatDim;
1994 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1995 {
1996 return Fail("%s: Operation has invalid inputs", __func__);
1997 }
1998
1999 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2000 if (!outputOperand)
2001 {
2002 return Fail("%s: Operation has no outputs", __func__);
2003 }
2004
Keith Davis6e4081f2020-09-03 13:17:21 +01002005 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
2006 armnn::TensorShape outputShape = outputInfo.GetShape();
2007 const bool isDynamicTensor = IsDynamicTensor(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002008 //
2009 // handle negative concat dims along the lines of tensorflow as described here:
2010 // https://www.tensorflow.org/api_docs/python/tf/concat
2011 // "negative axis refers to axis + rank(values)-th dimension"
2012 //
2013 if (concatDim < 0)
2014 {
2015 concatDim += outputShape.GetNumDimensions();
2016 }
2017
2018 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2019 {
2020 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2021 }
2022
2023 std::vector<LayerInputHandle> inputHandles;
2024 std::vector<armnn::TensorShape> inputShapes;
2025
2026 inputHandles.reserve(numInputTensors);
2027 inputShapes.reserve(numInputTensors);
2028
Keith Davis6e4081f2020-09-03 13:17:21 +01002029 bool inputsHaveBeenReshaped = false;
2030 unsigned int tensorDimensionsAdded = 0;
Mike Kellyb8805202019-07-31 17:25:43 +01002031 for (uint32_t i = 0; i < numInputTensors; ++i)
2032 {
2033 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2034 if (!operand)
2035 {
2036 return Fail("%s: Operation has invalid inputs", __func__);
2037 }
2038
Teresa Charlin3b959602019-10-31 17:05:47 +00002039 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2040 if (!operandInputHandle.IsValid())
2041 {
2042 return Fail("%s: Operation has invalid inputs", __func__);
2043 }
Mike Kellyb8805202019-07-31 17:25:43 +01002044
Keith Davis6e4081f2020-09-03 13:17:21 +01002045 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002046 if (operandShape.GetNumDimensions() == 0)
2047 {
2048 return Fail("%s: Operands with rank 0 are not supported", __func__);
2049 }
2050
2051 if (RequiresReshape(operandShape))
2052 {
2053 inputsHaveBeenReshaped = true;
2054
2055 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2056
2057 // Expand the tensor to three dimensions
2058 if (operandShape.GetNumDimensions() == 2)
2059 {
2060 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2061 tensorDimensionsAdded = 1;
2062 }
2063 else
2064 {
2065 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2066 tensorDimensionsAdded = 2;
2067 }
2068
Kevin Mayaed08ac2019-12-12 16:33:31 +00002069 armnn::ReshapeDescriptor reshapeDescriptor;
2070 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2071
2072 bool isSupported = false;
2073 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2074 IsReshapeSupported,
2075 data.m_Backends,
2076 isSupported,
2077 operandInputHandle.GetTensorInfo(),
2078 reshapeInfo,
2079 reshapeDescriptor);
Keith Davis6e4081f2020-09-03 13:17:21 +01002080
Kevin Mayaed08ac2019-12-12 16:33:31 +00002081 if (!isSupported)
2082 {
2083 return false;
2084 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002085 armnn::IConnectableLayer& newReshape = AddReshapeLayer(*data.m_Network, operandInputHandle, reshapeInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002086
2087 // Point to the reshape operation rather then the input operation
Keith Davis6e4081f2020-09-03 13:17:21 +01002088 operandShape = reshapeInfo.GetShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002089 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2090 }
2091
2092 inputShapes.emplace_back(operandShape);
2093 inputHandles.emplace_back(operandInputHandle);
2094
2095 if (!inputHandles.back().IsValid())
2096 {
2097 return Fail("%s: Operation has invalid inputs", __func__);
2098 }
2099 }
2100
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002101 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002102
2103 if (inputsHaveBeenReshaped)
2104 {
2105 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2106 concatDim += tensorDimensionsAdded;
2107
2108 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2109 if (tensorDimensionsAdded == 1)
2110 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002111 if (IsDynamicTensor(outputInfo))
2112 {
2113 outputShape = armnn::TensorShape({1, 0, 0}, {true, false, false});
2114 }
2115 else
2116 {
2117 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2118 }
Mike Kellyb8805202019-07-31 17:25:43 +01002119 }
2120 else if (tensorDimensionsAdded == 2)
2121 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002122 if (IsDynamicTensor(outputInfo))
2123 {
2124 outputShape = armnn::TensorShape({1, 1, 0}, {true, true, false});
2125 }
2126 else
2127 {
2128 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2129 }
Mike Kellyb8805202019-07-31 17:25:43 +01002130 }
2131 }
2132
2133 // Check if permutations is required and get the pair of permutations required for the concatenation.
2134 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2135 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
Keith Davis6e4081f2020-09-03 13:17:21 +01002136 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
Mike Kellyb8805202019-07-31 17:25:43 +01002137
Keith Davis6e4081f2020-09-03 13:17:21 +01002138 bool needPermute = CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(),
2139 concatDim,
2140 permutationPair);
Mike Kellyb8805202019-07-31 17:25:43 +01002141
Keith Davis6e4081f2020-09-03 13:17:21 +01002142 // Only relevant to static tensors as dynamic output tensors will be transposed as a result of inferring from input
2143 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002144 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002145 if (needPermute)
2146 {
2147 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
2148 }
2149
2150 outputInfo.SetShape(outputShape);
Mike Kellyb8805202019-07-31 17:25:43 +01002151 }
Mike Kellyb8805202019-07-31 17:25:43 +01002152 // this is no-op for identity swizzles, otherwise it replaces both
2153 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002154 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002155 {
2156 return false;
2157 }
Mike Kellyb8805202019-07-31 17:25:43 +01002158
2159 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2160 armnn::OriginsDescriptor concatDescriptor;
2161
2162 try
2163 {
2164 // The concat descriptor is always created across the only supported concat dimension
2165 // 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 +01002166 concatDescriptor = armnn::CreateDescriptorForConcatenation(inputShapes.begin(),
2167 inputShapes.end(),
2168 concatDim);
2169 } catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002170 {
2171 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2172 }
2173
2174 // Validate the output shape is correct given the input shapes based on the
2175 // 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 +01002176 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002177 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002178 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2179 {
2180 return Fail("%s: Error validating the output shape for concat", __func__);
2181 }
Mike Kellyb8805202019-07-31 17:25:43 +01002182 }
2183
2184 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2185 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
Keith Davis6e4081f2020-09-03 13:17:21 +01002186 [](const LayerInputHandle& h)->const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
Mike Kellyb8805202019-07-31 17:25:43 +01002187
Keith Davis6e4081f2020-09-03 13:17:21 +01002188 bool isSupported = false;
2189 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported){
2190 FORWARD_LAYER_SUPPORT_FUNC(__func__, IsConcatSupported, data.m_Backends, isSupported, inputTensorInfos,
2191 outputInfo, concatDescriptor);
2192 };
2193
2194 if (!isDynamicTensor)
2195 {
2196 validateFunc(outputInfo, isSupported);
2197 }
2198 else
2199 {
2200 isSupported = AreDynamicTensorsSupported();
2201 }
2202
Mike Kellyb8805202019-07-31 17:25:43 +01002203 if (!isSupported)
2204 {
2205 return false;
2206 }
2207
2208 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2209 assert(layer != nullptr);
2210 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002211 // Connect inputs to the layer
2212 const int numInputSlots = layer->GetNumInputSlots();
2213 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2214 for (int i = 0; i < numInputSlots; ++i)
2215 {
2216 // connect the input directly to the merge (concat) layer
2217 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2218 }
2219
Keith Davis6e4081f2020-09-03 13:17:21 +01002220 // Transpose the output shape
2221 auto transposeOutputShape = [&](){
Mike Kelly4a956582020-02-28 10:32:09 +00002222 armnn::TransposeDescriptor transposeDesc;
2223 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002224 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2225 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2226 permutationPair.second);
Keith Davis6e4081f2020-09-03 13:17:21 +01002227 isSupported = false;
Kevin Mayaed08ac2019-12-12 16:33:31 +00002228 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002229 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002230 data.m_Backends,
2231 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002232 inputTransposeInfo,
2233 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002234 transposeDesc);
Keith Davis6e4081f2020-09-03 13:17:21 +01002235
Kevin Mayaed08ac2019-12-12 16:33:31 +00002236 if (!isSupported)
2237 {
2238 return false;
2239 }
Mike Kellyb8805202019-07-31 17:25:43 +01002240 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Keith Davis6e4081f2020-09-03 13:17:21 +01002241 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network, layer->GetOutputSlot(0),
Mike Kelly4a956582020-02-28 10:32:09 +00002242 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002243 layer = &deswizzleLayer;
Keith Davis6e4081f2020-09-03 13:17:21 +01002244
2245 return true;
2246 };
2247
2248 if (needPermute && !isDynamicTensor)
2249 {
2250 transposeOutputShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002251 }
2252
2253 if (inputsHaveBeenReshaped)
2254 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002255 if (isDynamicTensor)
2256 {
2257 // Infer the output shapes of concat if outputs are type 1 dynamic
2258 layer->GetOutputSlot(0).IsTensorInfoSet();
2259 if (!ValidateConcatOutputShape(inputShapes,
2260 layer->GetOutputSlot(0).GetTensorInfo().GetShape(),
2261 concatDim))
2262 {
2263 return Fail("%s: Error validating the output shape for concat", __func__);
2264 }
2265 transposeOutputShape();
2266 }
2267
Mike Kellyb8805202019-07-31 17:25:43 +01002268 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
2269
2270 // Undo the reshape knowing the amount of dimensions added
2271 if (tensorDimensionsAdded == 1)
2272 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002273 afterConcatInfo.SetShape(
2274 armnn::TensorShape({afterConcatInfo.GetShape()[1], afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002275 }
2276 else if (tensorDimensionsAdded == 2)
2277 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002278 afterConcatInfo.SetShape(armnn::TensorShape({afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002279 }
2280
Kevin Mayaed08ac2019-12-12 16:33:31 +00002281 armnn::ReshapeDescriptor reshapeDescriptor;
2282 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
Keith Davis6e4081f2020-09-03 13:17:21 +01002283 armnn::TensorInfo concatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Kevin Mayaed08ac2019-12-12 16:33:31 +00002284
Keith Davis6e4081f2020-09-03 13:17:21 +01002285 isSupported = false;
2286 auto validateReshapeFunc = [&](const armnn::TensorInfo& afterConcatInfo, bool& isSupported){
2287 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2288 IsReshapeSupported,
2289 data.m_Backends,
2290 isSupported,
2291 concatInfo,
2292 afterConcatInfo,
2293 reshapeDescriptor);
2294 };
2295
2296 if (!IsDynamicTensor(afterConcatInfo))
2297 {
2298 validateReshapeFunc(afterConcatInfo, isSupported);
2299 }
2300 else
2301 {
2302 isSupported = AreDynamicTensorsSupported();
2303 }
2304
Kevin Mayaed08ac2019-12-12 16:33:31 +00002305 if (!isSupported)
2306 {
2307 return false;
2308 }
2309
Keith Davis6e4081f2020-09-03 13:17:21 +01002310 layer = &AddReshapeLayer(*data.m_Network, layer->GetOutputSlot(0), afterConcatInfo);
2311 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
2312 0,
2313 *layer,
2314 model,
2315 data,
2316 nullptr,
2317 validateReshapeFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002318 }
2319
Keith Davis6e4081f2020-09-03 13:17:21 +01002320 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002321}
2322
2323template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002324 typename HalOperation = typename HalPolicy::Operation,
2325 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002326bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2327{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002328 using HalOperand = typename HalPolicy::Operand;
2329 using HalOperandType = typename HalPolicy::OperandType;
2330
2331 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002332 if (!input.IsValid())
2333 {
2334 return Fail("%s: Operation has invalid inputs", __func__);
2335 }
2336
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002337 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002338 if (!output)
2339 {
2340 return Fail("%s: Could not read output 0", __func__);
2341 }
2342
2343 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002344 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002345
2346 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002347 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2348 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002349
2350 if (!weightsPin.IsValid() || !biasPin.IsValid())
2351 {
2352 return Fail("%s: Operation has invalid inputs", __func__);
2353 }
2354
2355 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002356 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002357 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2358
2359 armnn::Convolution2dDescriptor desc;
2360 desc.m_DataLayout = armnn::DataLayout::NHWC;
2361 ActivationFn activation;
2362
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002363 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002364 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002365 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2366 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2367 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2368 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2369 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2370 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002371 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002372 {
2373 return Fail("%s: Operation has invalid inputs", __func__);
2374 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002375 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002376 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002377 {
2378 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002379 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2380 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2381 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002382 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002383 {
2384 return Fail("%s: Operation has invalid inputs", __func__);
2385 }
2386
2387 const uint32_t kernelX = weights.GetShape()[2];
2388 const uint32_t kernelY = weights.GetShape()[1];
2389 const uint32_t inputX = inputInfo.GetShape()[2];
2390 const uint32_t inputY = inputInfo.GetShape()[1];
2391
2392 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2393 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002394 }
2395 else
2396 {
2397 return Fail("%s: Unsupported number of operation inputs", __func__);
2398 }
2399
2400 desc.m_BiasEnabled = true;
2401 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2402
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002403 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002404 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2405 {
2406 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2407 IsConvolution2dSupported,
2408 data.m_Backends,
2409 isSupported,
2410 inputInfo,
2411 outputInfo,
2412 desc,
2413 weights.GetInfo(),
2414 biases);
2415 };
2416
2417 if(!IsDynamicTensor(outputInfo))
2418 {
2419 validateFunc(outputInfo, isSupported);
2420 }
2421 else
2422 {
2423 isSupported = AreDynamicTensorsSupported();
2424 }
2425
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002426 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002427 {
2428 return false;
2429 }
2430
2431 armnn::IConnectableLayer* startLayer =
2432 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2433
2434 if (!startLayer)
2435 {
2436 return Fail("%s: AddConvolution2dLayer failed", __func__);
2437 }
2438
Mike Kellyb5fdf382019-06-11 16:35:25 +01002439 input.Connect(startLayer->GetInputSlot(0));
2440
Kevin Mayfcf2a152020-09-08 16:06:32 +01002441 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2442 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002443}
2444
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002445template<typename HalPolicy,
2446 typename HalOperation = typename HalPolicy::Operation,
2447 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002448bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2449{
2450 using HalOperand = typename HalPolicy::Operand;
2451 using HalOperandType = typename HalPolicy::OperandType;
2452
2453 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2454 if (!input.IsValid() )
2455 {
2456 return Fail("%s: Operation has invalid inputs", __func__);
2457 }
2458
2459 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2460 unsigned int rank = inputInfo.GetNumDimensions();
2461 if (rank != 4)
2462 {
2463 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2464 }
2465
2466 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2467 if (!output)
2468 {
2469 return Fail("%s: Could not read output 0", __func__);
2470 }
2471
2472 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002473
2474 armnn::DepthToSpaceDescriptor descriptor;
2475
2476 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2477 if (descriptor.m_BlockSize <= 1)
2478 {
2479 return Fail("%s: Block size must be at least 1 in all dimensions");
2480 }
2481
2482 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002483 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002484 {
2485 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2486 }
2487
2488 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002489 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2490 {
2491 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2492 IsDepthToSpaceSupported,
2493 data.m_Backends,
2494 isSupported,
2495 inputInfo,
2496 outputInfo,
2497 descriptor);
2498 };
2499
2500 if(!IsDynamicTensor(outputInfo))
2501 {
2502 validateFunc(outputInfo, isSupported);
2503 }
2504 else
2505 {
2506 isSupported = AreDynamicTensorsSupported();
2507 }
2508
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002509 if (!isSupported)
2510 {
2511 return false;
2512 }
2513
2514 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2515 assert(layer != nullptr);
2516 input.Connect(layer->GetInputSlot(0));
2517
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002518 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002519}
2520
2521template<typename HalPolicy,
2522 typename HalOperation = typename HalPolicy::Operation,
2523 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002524bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2525{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002526 using HalOperand = typename HalPolicy::Operand;
2527 using HalOperandType = typename HalPolicy::OperandType;
2528
2529 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002530
2531 if (!input.IsValid())
2532 {
2533 return Fail("%s: Operation has invalid inputs", __func__);
2534 }
2535
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002536 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002537
2538 if (!output)
2539 {
2540 return Fail("%s: Could not read output 0", __func__);
2541 }
2542
2543 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002544 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002545
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002546 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002547 // 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 +01002548 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002549
2550 if (weightsOperand == nullptr)
2551 {
2552 return Fail("%s: Operand is invalid", __func__);
2553 }
2554 armnn::DepthwiseConvolution2dDescriptor desc;
2555 desc.m_DataLayout = armnn::DataLayout::NHWC;
2556
Mike Kellyb5fdf382019-06-11 16:35:25 +01002557 // Reinterpret weight data as [ H, W, I, M ]
2558 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2559 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002560 inputInfo.GetShape()[3],
2561 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002562
2563 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2564 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2565
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002566 const ConstTensorPin weightsPin =
2567 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2568 1,
2569 model,
2570 data,
2571 HWIMToMIHW,
2572 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002573
2574 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002575 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002576
2577 if (!weightsPin.IsValid() || !biasPin.IsValid())
2578 {
2579 return Fail("%s: Operation has invalid inputs", __func__);
2580 }
2581
2582 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2583 armnn::ConstTensor bias = biasPin.GetConstTensor();
2584 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2585
2586 ActivationFn activation;
2587
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002588 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002589 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002590 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2591 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2592 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2593 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2594 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2595 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002596 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002597 {
2598 return Fail("%s: Operation has invalid inputs", __func__);
2599 }
2600 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002601 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002602 {
2603 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002604 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2605 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2606 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002607 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002608 {
2609 return Fail("%s: Operation has invalid inputs", __func__);
2610 }
2611
2612 const uint32_t kernelX = weights.GetShape()[3];
2613 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002614 const uint32_t inputX = inputInfo.GetShape()[2];
2615 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002616
2617 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2618 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2619 }
2620 else
2621 {
2622 return Fail("%s: Unsupported number of operation inputs", __func__);
2623 }
2624
2625 desc.m_BiasEnabled = true;
2626 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2627
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002628 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002629 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2630 {
2631 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2632 IsDepthwiseConvolutionSupported,
2633 data.m_Backends,
2634 isSupported,
2635 inputInfo,
2636 outputInfo,
2637 desc,
2638 weights.GetInfo(),
2639 biases);
2640 };
2641
2642 if(!IsDynamicTensor(outputInfo))
2643 {
2644 validateFunc(outputInfo, isSupported);
2645 }
2646 else
2647 {
2648 isSupported = AreDynamicTensorsSupported();
2649 }
2650
2651
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002652 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002653 {
2654 return false;
2655 }
2656
2657 armnn::IConnectableLayer* startLayer =
2658 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2659 if (!startLayer)
2660 {
2661 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2662 }
2663
Mike Kellyb5fdf382019-06-11 16:35:25 +01002664 input.Connect(startLayer->GetInputSlot(0));
2665
Kevin Mayfcf2a152020-09-08 16:06:32 +01002666 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2667 data, nullptr, validateFunc, activation);
arovir01b0717b52018-09-05 17:03:25 +01002668}
2669
Mike Kelly3c673942019-07-25 09:26:06 +01002670template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002671 typename HalOperation = typename HalPolicy::Operation,
2672 typename HalModel = typename HalPolicy::Model>
2673bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002674{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002675 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002676
2677 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2678 if (!input.IsValid())
2679 {
2680 return Fail("%s: Operation has invalid input", __func__);
2681 }
2682
Sadik Armagan98c0f662019-11-21 15:54:36 +00002683 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2684 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2685 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2686 {
2687 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2688 }
2689
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002690 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002691 if (!outputOperand)
2692 {
2693 return Fail("%s: Operation has invalid outputs", __func__);
2694 }
2695
2696 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002697
2698 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002699 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2700 {
2701 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2702 IsDequantizeSupported,
2703 data.m_Backends,
2704 isSupported,
2705 inputInfo,
2706 outputInfo);
2707 };
2708
2709 if(IsDynamicTensor(outputInfo))
2710 {
2711 isSupported = AreDynamicTensorsSupported();
2712 }
2713 else
2714 {
2715 validateFunc(outputInfo, isSupported);
2716 }
2717
Mike Kelly46272802019-08-14 17:00:48 +01002718 if (!isSupported)
2719 {
2720 return false;
2721 }
2722
2723 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2724 assert(layer != nullptr);
2725 input.Connect(layer->GetInputSlot(0));
2726
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002727 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002728}
2729
2730template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002731 typename HalOperation = typename HalPolicy::Operation,
2732 typename HalModel = typename HalPolicy::Model>
2733bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002734{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002735 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002736
2737 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2738 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2739
2740 if (!input0.IsValid() || !input1.IsValid())
2741 {
2742 return Fail("%s: Operation has invalid inputs", __func__);
2743 }
2744
2745 // The FuseActivation parameter is always the input index 2
2746 // and it should be optional
2747 ActivationFn activationFunction;
2748 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2749 {
2750 return Fail("%s: Operation has invalid inputs", __func__);
2751 }
2752
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002753 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002754 if (!output)
2755 {
2756 return Fail("%s: Could not read output 0", __func__);
2757 }
2758
2759 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002760
2761 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002762 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2763 {
2764 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2765 IsDivisionSupported,
2766 data.m_Backends,
2767 isSupported,
2768 input0.GetTensorInfo(),
2769 input1.GetTensorInfo(),
2770 outputInfo);
2771 };
2772
2773 if(!IsDynamicTensor(outputInfo))
2774 {
2775 validateFunc(outputInfo, isSupported);
2776 }
2777 else
2778 {
2779 isSupported = AreDynamicTensorsSupported();
2780 }
2781
Mike Kelly46272802019-08-14 17:00:48 +01002782 if (!isSupported)
2783 {
2784 return false;
2785 }
2786
2787 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01002788
Kevin Mayfcf2a152020-09-08 16:06:32 +01002789 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2790 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01002791 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01002792 return false;
Mike Kelly46272802019-08-14 17:00:48 +01002793 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01002794
2795 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2796 data, nullptr, validateFunc, activationFunction);
2797
Mike Kelly46272802019-08-14 17:00:48 +01002798}
2799
2800template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002801 typename HalOperation = typename HalPolicy::Operation,
2802 typename HalModel = typename HalPolicy::Model>
2803bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002804{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002805 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002806
2807 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2808 if (!input.IsValid())
2809 {
2810 return Fail("%s: Operation has invalid inputs", __func__);
2811 }
2812
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002813 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002814 if (!outputOperand)
2815 {
2816 return Fail("%s: Operation has invalid outputs", __func__);
2817 }
2818
2819 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002820
2821 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002822 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2823 {
2824 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2825 IsFloorSupported,
2826 data.m_Backends,
2827 isSupported,
2828 input.GetTensorInfo(),
2829 outputInfo);
2830 };
2831
2832 if(!IsDynamicTensor(outputInfo))
2833 {
2834 validateFunc(outputInfo, isSupported);
2835 }
2836 else
2837 {
2838 isSupported = AreDynamicTensorsSupported();
2839 }
2840
Mike Kelly46272802019-08-14 17:00:48 +01002841 if (!isSupported)
2842 {
2843 return false;
2844 }
2845
2846 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2847 assert(layer != nullptr);
2848 input.Connect(layer->GetInputSlot(0));
2849
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002850 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002851}
2852
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002853inline bool IsQSymm8(const V1_0::Operand&)
2854{
2855 return false;
2856}
2857
Kevin May42477c12020-03-26 13:34:14 +00002858#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002859
2860inline bool IsQSymm8(const V1_2::Operand& operand)
2861{
2862 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2863}
2864
2865#endif
2866
Kevin May42477c12020-03-26 13:34:14 +00002867#ifdef ARMNN_ANDROID_NN_V1_3
2868
2869inline bool IsQSymm8(const V1_3::Operand& operand)
2870{
2871 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2872}
2873
2874#endif
2875
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002876enum class DequantizeStatus
2877{
2878 SUCCESS,
2879 NOT_REQUIRED,
2880 INVALID_OPERAND
2881};
2882
2883using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2884
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002885template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002886 typename HalOperation = typename HalPolicy::Operation,
2887 typename HalModel = typename HalPolicy::Model>
2888DequantizeResult DequantizeIfRequired(size_t operand_index,
2889 const HalOperation& operation,
2890 const HalModel& model,
2891 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002892{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002893 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002894
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002895 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002896 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002897 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002898 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002899 }
2900
2901 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2902 {
2903 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002904 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002905 }
2906
2907 const size_t weightsInputIndex = operation.inputs[operand_index];
2908
2909 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2910 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002911 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002912 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002913 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002914 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002915 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2916 {
2917 continue;
2918 }
2919
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002920 size_t outOpIndex = weightsInputIndex + 1;
2921 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002922 {
2923 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002924 }
2925
2926 if (outOpIndex != weightsInputIndex)
2927 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002928 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002929 }
2930
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002931 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002932 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002933
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002934 if (!IsQSymm8(*operand))
2935 {
2936 // Only supporting dequantize from QSYMM8 to FLOAT
2937 break;
2938 }
2939
2940 // Allocate a new buffer for the dequantized data and manually dequantize
2941 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2942 if (!startValue)
2943 {
2944 // Failed to get the operand address
2945 break;
2946 }
2947
2948 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2949 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002950 const float quantizationScale = operand->scale;
2951
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002952 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2953 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2954 {
2955 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002956 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002957 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2958 }
2959
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002960 // Construct tensor info for dequantized ConstTensor
2961 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2962 operand->dimensions.data(),
2963 armnn::DataType::Float32);
2964
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002965 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2966 std::move(tensorInfo),
2967 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002968 }
2969
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002970 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002971}
2972
2973template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002974 typename HalOperation = typename HalPolicy::Operation,
2975 typename HalModel = typename HalPolicy::Model>
2976ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2977 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002978 const ConversionData& data,
2979 size_t operandIndex,
2980 bool optional = false)
2981{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002982 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2983
2984 DequantizeStatus status = std::get<3>(dequantized);
2985 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002986 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002987 case DequantizeStatus::INVALID_OPERAND:
2988 {
2989 // return invalid const tensor pin
2990 return ConstTensorPin();
2991 }
2992 case DequantizeStatus::NOT_REQUIRED:
2993 {
2994 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2995 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
2996 }
2997 case DequantizeStatus::SUCCESS:
2998 default:
2999 {
3000 return ConstTensorPin(
3001 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
3002 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003003 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003004}
3005
3006
Mike Kelly46272802019-08-14 17:00:48 +01003007template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003008 typename HalOperation = typename HalPolicy::Operation,
3009 typename HalModel = typename HalPolicy::Model>
3010bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003011{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003012 using HalOperand = typename HalPolicy::Operand;
3013
Mike Kelly46272802019-08-14 17:00:48 +01003014 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3015 if (!input.IsValid())
3016 {
3017 return Fail("%s: Operation has invalid inputs", __func__);
3018 }
3019
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003020 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003021 if (!output)
3022 {
3023 return Fail("%s: Could not read output 0", __func__);
3024 }
3025
3026 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3027 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3028
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003029 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
3030 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003031
3032 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01003033 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003034 return Fail("%s: Operation has invalid weights", __func__);
3035 }
3036
3037 if (!biasPin.IsValid())
3038 {
3039 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003040 }
3041
3042 armnn::ConstTensor weights = weightsPin.GetConstTensor();
3043 armnn::ConstTensor bias = biasPin.GetConstTensor();
3044 armnn::TensorInfo reshapedInfo = inputInfo;
3045
3046 try
3047 {
3048 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003049 }
3050 catch (const std::exception& e)
3051 {
Mike Kelly46272802019-08-14 17:00:48 +01003052 return Fail("%s: %s", __func__, e.what());
3053 }
3054
3055 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
3056 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
3057
3058 ActivationFn activationFunction;
3059 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3060 {
3061 return Fail("%s: Operation has invalid inputs", __func__);
3062 }
3063
3064 armnn::FullyConnectedDescriptor desc;
3065 desc.m_TransposeWeightMatrix = true;
3066 desc.m_BiasEnabled = true;
3067
FinnWilliamsArm7b8d2e62020-01-08 14:57:47 +00003068 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
3069 weights.GetInfo().GetShape(),
3070 outputInfo.GetShape(),
3071 desc.m_TransposeWeightMatrix))
3072 {
3073 return Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3074 }
3075
Mike Kelly46272802019-08-14 17:00:48 +01003076 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003077 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3078 {
3079 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly46272802019-08-14 17:00:48 +01003080 IsFullyConnectedSupported,
3081 data.m_Backends,
3082 isSupported,
3083 reshapedInfo,
3084 outputInfo,
3085 weights.GetInfo(),
3086 bias.GetInfo(),
3087 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003088 };
3089
3090 if(!IsDynamicTensor(outputInfo))
3091 {
3092 validateFunc(outputInfo, isSupported);
3093 }
3094 else
3095 {
3096 isSupported = AreDynamicTensorsSupported();
3097 }
3098
Mike Kelly46272802019-08-14 17:00:48 +01003099 if (!isSupported)
3100 {
3101 return false;
3102 }
3103
3104 armnn::IConnectableLayer* startLayer =
3105 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
Mike Kelly46272802019-08-14 17:00:48 +01003106
Kevin Mayfcf2a152020-09-08 16:06:32 +01003107 if (inputInfo.GetNumDimensions() > 2U)
Mike Kelly46272802019-08-14 17:00:48 +01003108 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003109 armnn::ReshapeDescriptor reshapeDescriptor;
3110 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
Mike Kelly46272802019-08-14 17:00:48 +01003111
Kevin Mayfcf2a152020-09-08 16:06:32 +01003112 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3113 assert(reshapeLayer != nullptr);
3114 input.Connect(reshapeLayer->GetInputSlot(0));
3115 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3116 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003117 }
3118 else
3119 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003120 input.Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003121 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003122
3123 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3124 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003125}
3126
3127template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003128 typename HalOperation = typename HalPolicy::Operation,
3129 typename HalModel = typename HalPolicy::Model>
3130bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003131{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003132 using HalOperand = typename HalPolicy::Operand;
3133
Mike Kelly999e2092019-08-15 10:46:46 +01003134 if (operation.inputs.size() != 1)
3135 {
3136 return Fail("%s: Optional inputs are not supported", __func__);
3137 }
3138
Mike Kelly46272802019-08-14 17:00:48 +01003139 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3140 if (!input.IsValid())
3141 {
3142 return Fail("%s: Operation has invalid inputs", __func__);
3143 }
3144
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003145 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003146 if (!output)
3147 {
3148 return Fail("%s: Could not read output 0", __func__);
3149 }
3150
3151 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3152 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3153
Mike Kelly46272802019-08-14 17:00:48 +01003154 if (outputInfo.GetNumDimensions() != 4u)
3155 {
3156 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3157 }
3158
3159 armnn::L2NormalizationDescriptor desc;
3160 desc.m_DataLayout = armnn::DataLayout::NHWC;
3161
3162 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003163 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3164 {
3165 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3166 IsL2NormalizationSupported,
3167 data.m_Backends,
3168 isSupported,
3169 inputInfo,
3170 outputInfo,
3171 desc);
3172 };
3173
3174 if(!IsDynamicTensor(outputInfo))
3175 {
3176 validateFunc(outputInfo, isSupported);
3177 }
3178 else
3179 {
3180 isSupported = AreDynamicTensorsSupported();
3181 }
3182
Mike Kelly46272802019-08-14 17:00:48 +01003183 if (!isSupported)
3184 {
3185 return false;
3186 }
3187
3188 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3189 assert(layer != nullptr);
3190 input.Connect(layer->GetInputSlot(0));
3191
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003192 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003193}
3194
3195template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003196 typename HalOperation = typename HalPolicy::Operation,
3197 typename HalModel = typename HalPolicy::Model>
3198bool ConvertLocalResponseNormalization(const HalOperation& operation,
3199 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003200 ConversionData& data)
3201{
Mike Kelly999e2092019-08-15 10:46:46 +01003202 if (operation.inputs.size() != 5)
3203 {
3204 return Fail("%s: Optional inputs are not supported", __func__);
3205 }
3206
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003207 using HalOperand = typename HalPolicy::Operand;
3208 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003209
3210 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3211 if (!input.IsValid())
3212 {
3213 return Fail("%s: Operation has invalid inputs", __func__);
3214 }
3215
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003216 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003217 if (!output)
3218 {
3219 return Fail("%s: Could not read output 0", __func__);
3220 }
3221
3222 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3223 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3224
Mike Kelly46272802019-08-14 17:00:48 +01003225 if (outputInfo.GetNumDimensions() != 4u)
3226 {
3227 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3228 }
3229
3230 armnn::NormalizationDescriptor descriptor;
3231 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3232 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3233 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3234
3235 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003236 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003237 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3238 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3239 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3240 {
3241 return Fail("%s: Operation has invalid inputs", __func__);
3242 }
3243
3244 // ArmNN expects normSize to be the full size of the normalization
3245 // window rather than the radius as in AndroidNN.
3246 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3247
3248 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003249 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3250 {
3251 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3252 IsNormalizationSupported,
3253 data.m_Backends,
3254 isSupported,
3255 inputInfo,
3256 outputInfo,
3257 descriptor);
3258 };
3259
3260 if(!IsDynamicTensor(outputInfo))
3261 {
3262 validateFunc(outputInfo, isSupported);
3263 }
3264 else
3265 {
3266 isSupported = AreDynamicTensorsSupported();
3267 }
3268
Mike Kelly46272802019-08-14 17:00:48 +01003269 if (!isSupported)
3270 {
3271 return false;
3272 }
3273
3274
3275 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3276 assert(layer != nullptr);
3277 input.Connect(layer->GetInputSlot(0));
3278
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003279 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003280}
3281
3282template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003283 typename HalOperation = typename HalPolicy::Operation,
3284 typename HalModel = typename HalPolicy::Model>
3285bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003286{
Mike Kelly46272802019-08-14 17:00:48 +01003287 armnn::ActivationDescriptor desc;
3288 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3289
3290 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3291}
3292
3293template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003294 typename HalOperation = typename HalPolicy::Operation,
3295 typename HalModel = typename HalPolicy::Model>
3296bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003297{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003298 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003299
3300 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3301 if (!input.IsValid())
3302 {
3303 return Fail("%s: Operation has invalid inputs", __func__);
3304 }
3305
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003306 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003307 if (!output)
3308 {
3309 return Fail("%s: Could not read output 0", __func__);
3310 }
3311
3312 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003313
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003314 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003315 if (!axisOperand)
3316 {
3317 return Fail("%s: Could not read input 1", __func__);
3318 }
3319
3320 std::vector<int32_t> axis;
3321 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3322 {
3323 return Fail("%s: Input 1 has invalid values", __func__);
3324 }
3325
3326 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3327
3328 // Convert the axis to unsigned int and remove duplicates.
3329 unsigned int rank = inputInfo.GetNumDimensions();
3330 std::set<unsigned int> uniqueAxis;
3331 std::transform(axis.begin(), axis.end(),
3332 std::inserter(uniqueAxis, uniqueAxis.begin()),
3333 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3334
3335 // Get the "keep dims" flag.
3336 int32_t keepDims = 0;
3337 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3338 {
3339 return Fail("%s: Could not read input 2", __func__);
3340 }
3341
3342 armnn::MeanDescriptor descriptor;
3343 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3344 descriptor.m_KeepDims = keepDims > 0;
3345
3346 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003347 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3348 {
3349 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3350 IsMeanSupported,
3351 data.m_Backends,
3352 isSupported,
3353 inputInfo,
3354 outputInfo,
3355 descriptor);
3356 };
3357
3358 if(!IsDynamicTensor(outputInfo))
3359 {
3360 validateFunc(outputInfo, isSupported);
3361 }
3362 else
3363 {
3364 isSupported = AreDynamicTensorsSupported();
3365 }
3366
Mike Kelly46272802019-08-14 17:00:48 +01003367 if (!isSupported)
3368 {
3369 return false;
3370 }
3371
3372 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3373 assert(layer != nullptr);
3374 input.Connect(layer->GetInputSlot(0));
3375
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003376 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003377}
3378
3379template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003380 typename HalOperation = typename HalPolicy::Operation,
3381 typename HalModel = typename HalPolicy::Model>
3382bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003383{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003384 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003385
3386 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3387 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3388
3389 if (!input0.IsValid() || !input1.IsValid())
3390 {
3391 return Fail("%s: Operation has invalid inputs", __func__);
3392 }
3393
3394 // The FuseActivation parameter is always the input index 2
3395 // and it should be optional
3396 ActivationFn activationFunction;
3397 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3398 {
3399 return Fail("%s: Operation has invalid inputs", __func__);
3400 }
3401
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003402 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003403
3404 if (outputOperand == nullptr)
3405 {
3406 return false;
3407 }
3408
3409 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003410
3411 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003412 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3413 {
3414 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3415 IsMultiplicationSupported,
3416 data.m_Backends,
3417 isSupported,
3418 input0.GetTensorInfo(),
3419 input1.GetTensorInfo(),
3420 outputInfo);
3421 };
3422
3423 if(!IsDynamicTensor(outputInfo))
3424 {
3425 validateFunc(outputInfo, isSupported);
3426 }
3427 else
3428 {
3429 isSupported = AreDynamicTensorsSupported();
3430 }
3431
Mike Kelly46272802019-08-14 17:00:48 +01003432 if (!isSupported)
3433 {
3434 return false;
3435 }
3436
3437 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
Mike Kelly46272802019-08-14 17:00:48 +01003438
3439 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3440 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3441
Kevin Mayfcf2a152020-09-08 16:06:32 +01003442 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3443 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01003444 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003445 return false;
3446 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01003447
Kevin Mayfcf2a152020-09-08 16:06:32 +01003448 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3449 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003450}
3451
3452template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003453 typename HalOperation = typename HalPolicy::Operation,
3454 typename HalModel = typename HalPolicy::Model>
3455bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003456{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003457 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003458
Mike Kelly3c673942019-07-25 09:26:06 +01003459 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3460 if (!input.IsValid())
3461 {
3462 return Fail("%s: Operation has invalid inputs", __func__);
3463 }
3464
3465 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3466 unsigned int rank = inputInfo.GetNumDimensions();
3467
3468 armnn::PadDescriptor descriptor;
3469 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3470 {
3471 return Fail("%s: Could not convert paddings", __func__);
3472 }
3473
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003474 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3475 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003476 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3477 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3478 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003479 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003480 {
3481 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3482 }
3483
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003484 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003485 if (!output)
3486 {
3487 return Fail("%s: Could not read output", __func__);
3488 }
3489
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003490 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003491
3492 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003493 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3494 {
3495 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3496 IsPadSupported,
3497 data.m_Backends,
3498 isSupported,
3499 inputInfo,
3500 outputInfo,
3501 descriptor);
3502 };
3503
3504 if(!IsDynamicTensor(outputInfo))
3505 {
3506 validateFunc(outputInfo, isSupported);
3507 }
3508 else
3509 {
3510 isSupported = AreDynamicTensorsSupported();
3511 }
3512
Mike Kelly3c673942019-07-25 09:26:06 +01003513 if (!isSupported)
3514 {
3515 return false;
3516 }
3517
3518 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3519 assert(layer != nullptr);
3520 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003521
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003522 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003523}
3524
Mike Kelly0a879362019-07-29 16:56:31 +01003525template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003526 typename HalOperation = typename HalPolicy::Operation,
3527 typename HalModel = typename HalPolicy::Model>
3528bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003529{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003530 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003531
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003532 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3533 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3534 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003535
3536 if (inputOperand == nullptr
3537 || requestedShapeOperand == nullptr
3538 || outputOperand == nullptr)
3539 {
3540 return Fail("%s: Operation has invalid inputs", __func__);
3541 }
3542
3543 if (requestedShapeOperand->dimensions.size() != 1)
3544 {
3545 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3546 __func__, requestedShapeOperand->dimensions.size());
3547 }
3548
3549 std::vector<int32_t> targetDimensions;
3550 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3551 {
3552 return Fail("%s: Could not read values of input 1", __func__);
3553 }
3554
3555 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3556
3557 Shape requestedShape;
3558 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3559 // function that resolves these values into a fully specified tensor shape.
3560 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3561 {
3562 return Fail("%s: Failed to resolve the requested shape", __func__);
3563 }
3564
Mike Kelly46272802019-08-14 17:00:48 +01003565 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3566 if (!input.IsValid())
3567 {
3568 return Fail("%s: Could not read input 0", __func__);
3569 }
3570
3571 armnn::ReshapeDescriptor reshapeDescriptor;
3572 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3573 requestedShape.dimensions.data());
3574
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003575 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3576
Mike Kelly46272802019-08-14 17:00:48 +01003577 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003578 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3579 {
3580 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3581 IsReshapeSupported,
3582 data.m_Backends,
3583 isSupported,
3584 input.GetTensorInfo(),
3585 outputInfo,
3586 reshapeDescriptor);
3587 };
3588
3589 if(!IsDynamicTensor(outputInfo))
3590 {
3591 validateFunc(outputInfo, isSupported);
3592 }
3593 else
3594 {
3595 isSupported = AreDynamicTensorsSupported();
3596 }
3597
Mike Kelly46272802019-08-14 17:00:48 +01003598 if (!isSupported)
3599 {
3600 return false;
3601 }
3602
3603 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3604 assert(layer != nullptr);
3605 input.Connect(layer->GetInputSlot(0));
3606
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003607 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003608}
3609
3610template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003611 typename HalOperation = typename HalPolicy::Operation,
3612 typename HalModel = typename HalPolicy::Model>
3613bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003614{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003615 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003616
Mike Kelly0a879362019-07-29 16:56:31 +01003617 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3618 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3619
3620 if (!input0.IsValid() || !input1.IsValid())
3621 {
3622 return Fail("%s: Operation has invalid inputs", __func__);
3623 }
3624
3625 // The FuseActivation parameter is always the input index 2
3626 // and it should be optional
3627 ActivationFn activationFunction;
3628 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3629 {
3630 return Fail("%s: Operation has invalid inputs", __func__);
3631 }
3632
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003633 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003634 if (!output)
3635 {
3636 return Fail("%s: Could not read output 0", __func__);
3637 }
3638
3639 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003640
3641 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003642 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3643 {
3644 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3645 IsSubtractionSupported,
3646 data.m_Backends,
3647 isSupported,
3648 input0.GetTensorInfo(),
3649 input1.GetTensorInfo(),
3650 outputInfo);
3651 };
3652
3653 if(IsDynamicTensor(outputInfo))
3654 {
3655 isSupported = AreDynamicTensorsSupported();
3656 }
3657 else
3658 {
3659 validateFunc(outputInfo, isSupported);
3660 }
3661
Mike Kelly0a879362019-07-29 16:56:31 +01003662 if (!isSupported)
3663 {
3664 return false;
3665 }
3666
3667 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
Mike Kelly0a879362019-07-29 16:56:31 +01003668
3669 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3670 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3671
Kevin Mayfcf2a152020-09-08 16:06:32 +01003672 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3673 if (!isReshapeSupported)
Mike Kelly0a879362019-07-29 16:56:31 +01003674 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003675 return false;
Mike Kelly0a879362019-07-29 16:56:31 +01003676 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003677 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3678 data, nullptr, validateFunc, activationFunction);
Mike Kelly0a879362019-07-29 16:56:31 +01003679}
3680
Finn Williams23b87b32019-07-30 11:44:05 +01003681template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003682 typename HalOperation = typename HalPolicy::Operation,
3683 typename HalModel = typename HalPolicy::Model>
3684bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003685{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003686 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003687
3688 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3689 if (!input.IsValid())
3690 {
3691 return Fail("%s: Operation has invalid inputs", __func__);
3692 }
3693
3694 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3695 unsigned int rank = inputInfo.GetNumDimensions();
3696 if (rank > 4)
3697 {
3698 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3699 }
3700
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003701 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003702 if (!output)
3703 {
3704 return Fail("%s: Could not read output 0", __func__);
3705 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003706
3707 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003708 {
3709 return Fail("%s: Dynamic output tensors are not supported", __func__);
3710 }
3711
3712 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3713 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003714 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003715
3716 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3717
3718 std::vector<int32_t> axis;
3719 if (!axisOperand)
3720 {
3721 axis.assign(dimensionSequence,
3722 dimensionSequence + rank);
3723 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003724 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003725 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003726 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003727 }
3728
3729 std::vector<uint32_t> outputDims;
3730 for (unsigned int i = 0; i < rank; i++)
3731 {
3732 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3733 auto currentDimension = inputInfo.GetShape()[i];
3734 if (skipSqueeze || currentDimension != 1)
3735 {
3736 outputDims.push_back(currentDimension);
3737 }
3738 }
3739
3740 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3741
3742 armnn::TensorInfo outputInfo = inputInfo;
3743 outputInfo.SetShape(outShape);
3744
3745 armnn::ReshapeDescriptor reshapeDesc;
3746 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3747
3748 bool isSupported = false;
3749 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3750 IsReshapeSupported,
3751 data.m_Backends,
3752 isSupported,
3753 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003754 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003755 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003756
Mike Kelly46272802019-08-14 17:00:48 +01003757 if (!isSupported)
3758 {
3759 return false;
3760 }
3761
3762 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3763 assert(layer != nullptr);
3764 input.Connect(layer->GetInputSlot(0));
3765
3766 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3767}
3768
3769template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003770 typename HalOperation = typename HalPolicy::Operation,
3771 typename HalModel = typename HalPolicy::Model>
3772bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003773{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003774 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003775
3776 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3777 if (!input.IsValid())
3778 {
3779 return Fail("%s: Operation has invalid inputs", __func__);
3780 }
3781
3782 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3783 unsigned int rank = inputInfo.GetNumDimensions();
3784 if (rank > 4)
3785 {
3786 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3787 }
3788
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003789 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003790 if (!output)
3791 {
3792 return Fail("%s: Could not read output 0", __func__);
3793 }
3794
3795 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003796
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003797 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3798 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3799 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003800
3801 std::vector<int32_t> beginValues;
3802 std::vector<int32_t> endValues;
3803 std::vector<int32_t> stridesValues;
3804
3805 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003806 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003807 {
3808 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3809 {
3810 return false;
3811 }
3812
3813 if (operandValues.size() != rank)
3814 {
3815 return false;
3816 }
3817
3818 return true;
3819 };
3820
3821 if (!ValidateInputOperands(*beginOperand, beginValues)
3822 || !ValidateInputOperands(*endOperand, endValues)
3823 || !ValidateInputOperands(*stridesOperand, stridesValues))
3824 {
3825 return Fail("%s: Operation has invalid input operand", __func__);
3826 }
3827
3828 // Stride cannot have value '0'
3829 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3830 {
3831 return Fail("%s: Stride must be non-zero value.", __func__);
3832 }
3833
3834 armnn::StridedSliceDescriptor descriptor;
3835 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3836 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3837 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3838 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3839
3840 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3841 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3842 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3843 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3844 {
3845 return Fail("%s: Operation has invalid inputs", __func__);
3846 }
3847
3848 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003849 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3850 {
3851 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3852 IsStridedSliceSupported,
3853 data.m_Backends,
3854 isSupported,
3855 inputInfo,
3856 outputInfo,
3857 descriptor);
3858 };
3859
3860 if(IsDynamicTensor(outputInfo))
3861 {
3862 isSupported = AreDynamicTensorsSupported();
3863 }
3864 else
3865 {
3866 validateFunc(outputInfo, isSupported);
3867 }
3868
Mike Kelly46272802019-08-14 17:00:48 +01003869 if (!isSupported)
3870 {
3871 return false;
3872 }
3873
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003874 // Check if slice can fit in a inferred output
3875 armnn::TensorShape inputShape = inputInfo.GetShape();
3876 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3877 {
3878 int stride = descriptor.m_Stride[i];
3879 int start = descriptor.GetStartForAxis(inputShape, i);
3880 int stop = descriptor.GetStopForAxis(inputShape, i, start);
3881
3882 if (descriptor.m_ShrinkAxisMask & (1 << i))
3883 {
3884 // If the difference between the start point and the end point of the slice on an axis being shrunk
3885 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3886 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3887 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3888 {
3889 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3890 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003891
3892 if(stride < 0)
3893 {
3894 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3895 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003896 }
3897 }
3898
Mike Kelly46272802019-08-14 17:00:48 +01003899 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3900 assert(layer != nullptr);
3901 input.Connect(layer->GetInputSlot(0));
3902
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003903 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003904}
3905
3906template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003907 typename HalOperation = typename HalPolicy::Operation,
3908 typename HalModel = typename HalPolicy::Model>
3909bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003910{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003911 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003912 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003913
3914 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3915 if (!input.IsValid())
3916 {
3917 return Fail("%s: Operation has invalid inputs", __func__);
3918 }
3919
3920 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3921 unsigned int rank = inputInfo.GetNumDimensions();
3922 if (rank > 4)
3923 {
3924 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3925 }
3926
3927 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3928 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003929 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003930
3931 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003932 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003933 {
Mike Kelly46272802019-08-14 17:00:48 +01003934 for (unsigned int i = rank; i > 0; i--)
3935 {
Matthew Sloyan9b088d92020-09-14 15:12:55 +01003936 perm[rank - i] = armnn::numeric_cast<int> (i - 1);
Mike Kelly46272802019-08-14 17:00:48 +01003937 }
3938 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003939 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003940 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003941 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003942 }
3943
3944 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3945
Mike Kelly4a956582020-02-28 10:32:09 +00003946 armnn::TransposeDescriptor transposeDesc;
3947 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003948
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003949 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003950 if (!output)
3951 {
3952 return Fail("%s: Could not read output 0", __func__);
3953 }
3954
3955 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3956
3957 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003958 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3959 {
3960 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3961 IsTransposeSupported,
3962 data.m_Backends,
3963 isSupported,
3964 inputInfo,
3965 outputInfo,
3966 transposeDesc);
3967 };
3968
3969 if(IsDynamicTensor(outputInfo))
3970 {
3971 isSupported = AreDynamicTensorsSupported();
3972 }
3973 else
3974 {
3975 validateFunc(outputInfo, isSupported);
3976 }
3977
Mike Kelly46272802019-08-14 17:00:48 +01003978 if (!isSupported)
3979 {
3980 return false;
3981 }
3982
Mike Kelly4a956582020-02-28 10:32:09 +00003983 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003984 assert(layer != nullptr);
3985 input.Connect(layer->GetInputSlot(0));
3986
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003987 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003988}
3989
3990template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003991 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003992 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003993 typename HalModel = typename HalPolicy::Model>
3994bool ConvertBatchToSpaceNd(const HalOperation& operation,
3995 const HalModel& model,
3996 ConversionData& data)
3997{
Finn Williams23b87b32019-07-30 11:44:05 +01003998
3999 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4000 if (!input.IsValid())
4001 {
4002 return Fail("%s: Operation has invalid inputs", __func__);
4003 }
4004
4005 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4006 if (!output)
4007 {
4008 return Fail("%s: Could not read output 0", __func__);
4009 }
4010
4011 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004012
4013 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4014 if (!blockOperand)
4015 {
4016 return Fail("%s: Could not read input 1", __func__);
4017 }
4018
4019 // Convert the block operand to int32
4020 std::vector<int32_t> block;
4021 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4022 {
4023 return Fail("%s: Input 1 has invalid values", __func__);
4024 }
4025
4026 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4027
4028 unsigned int rank = inputInfo.GetNumDimensions();
4029 if (rank != 4)
4030 {
4031 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4032 }
4033
4034 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4035 {
4036 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4037 " greater than or equal to 1", __func__);
4038 }
4039
4040 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4041 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4042 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4043
Kevin May42477c12020-03-26 13:34:14 +00004044 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004045 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004046 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004047 }
4048 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4049 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4050
4051 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004052 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4053 {
4054 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4055 IsBatchToSpaceNdSupported,
4056 data.m_Backends,
4057 isSupported,
4058 inputInfo,
4059 outputInfo,
4060 batchToSpaceNdDesc);
4061 };
4062
4063 if(!IsDynamicTensor(outputInfo))
4064 {
4065 validateFunc(outputInfo, isSupported);
4066 }
4067 else
4068 {
4069 isSupported = AreDynamicTensorsSupported();
4070 }
4071
4072
Finn Williams23b87b32019-07-30 11:44:05 +01004073 if (!isSupported)
4074 {
4075 return false;
4076 }
4077
4078 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4079 assert(layer != nullptr);
4080 input.Connect(layer->GetInputSlot(0));
4081
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004082 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004083}
Mike Kelly0a879362019-07-29 16:56:31 +01004084
Finn Williamsd74c5052019-07-30 17:06:00 +01004085template<typename HalPolicy,
4086 typename HalOperation = typename HalPolicy::Operation,
4087 typename HalOperand = typename HalPolicy::Operand,
4088 typename HalModel = typename HalPolicy::Model>
4089bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4090{
4091 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4092 if (!input.IsValid())
4093 {
4094 return Fail("%s: Operation has invalid inputs", __func__);
4095 }
4096
4097 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4098 unsigned int rank = inputInfo.GetNumDimensions();
4099 unsigned int spatialDim = rank - 2;
4100
4101 if (rank != 4)
4102 {
4103 Fail("%s: Only inputs with rank 4 are supported", __func__);
4104 }
4105
4106 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4107 if (!output)
4108 {
4109 return Fail("%s: Could not read output 0", __func__);
4110 }
4111
4112 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004113
4114 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4115 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4116
4117 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4118 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4119 {
4120 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4121 }
4122
4123 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004124 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4125 {
4126 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4127 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004128 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4129 {
4130 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4131 }
4132
4133 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4134 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4135 {
4136 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4137 }
4138
4139 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4140 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004141 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4142 {
4143 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4144 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004145 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4146 {
4147 int paddingBeforeInput = paddings[i];
4148 int paddingAfterInput = paddings[i + 1];
4149 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4150 {
4151 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4152 }
4153
4154 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4155 }
4156
4157 armnn::SpaceToBatchNdDescriptor descriptor;
4158 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4159 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4160 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4161
Kevin May42477c12020-03-26 13:34:14 +00004162 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004163 {
4164 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4165 }
4166
4167 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004168 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4169 {
4170 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4171 IsSpaceToBatchNdSupported,
4172 data.m_Backends,
4173 isSupported,
4174 inputInfo,
4175 outputInfo,
4176 descriptor);
4177 };
4178
4179 if(IsDynamicTensor(outputInfo))
4180 {
4181 isSupported = AreDynamicTensorsSupported();
4182 }
4183 else
4184 {
4185 validateFunc(outputInfo, isSupported);
4186 }
4187
Finn Williamsd74c5052019-07-30 17:06:00 +01004188 if (!isSupported)
4189 {
4190 return false;
4191 }
4192
4193 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4194 assert(layer != nullptr);
4195 input.Connect(layer->GetInputSlot(0));
4196
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004197 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004198}
4199
saoste01b8471482018-10-10 09:44:51 +01004200} // namespace armnn_driver