blob: fa67f791c23b570843ab0d6655afab8a932b1265 [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>
arovir01b0717b52018-09-05 17:03:25 +010015
Matteo Martincigh00d6ed12019-11-28 17:13:24 +000016#include <armnnUtils/DataLayoutIndexed.hpp>
Mike Kelly4a956582020-02-28 10:32:09 +000017#include <armnnUtils/Transpose.hpp>
arovir01b0717b52018-09-05 17:03:25 +010018
Mike Kelly46272802019-08-14 17:00:48 +010019#include "1.0/FullyConnected.hpp"
20
arovir01b0717b52018-09-05 17:03:25 +010021#include <ActivationFunctor.h>
22#include <CpuExecutor.h>
23#include <OperationsUtils.h>
24
Aron Virginas-Tar0e7ab542019-04-10 15:02:31 +010025#include <boost/numeric/conversion/cast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010026#include <boost/test/tools/floating_point_comparison.hpp>
27
28#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010029#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010030
31namespace armnn_driver
32{
33
34///
35/// Helper classes
36///
37
Kevin Mayec1e5b82020-02-26 17:00:39 +000038#ifdef ARMNN_ANDROID_R
39using OperandType = android::nn::hal::OperandType;
40#endif
41
arovir01b0717b52018-09-05 17:03:25 +010042struct ConversionData
43{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010044 ConversionData(const std::vector<armnn::BackendId>& backends)
45 : m_Backends(backends)
46 , m_Network(nullptr, nullptr)
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);
311 unsigned int sizeDifference = std::abs(boost::numeric_cast<int>(inputDimensions0) -
312 boost::numeric_cast<int>(inputDimensions1));
313
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;
326 reshapedInfo.SetShape(armnn::TensorShape{ boost::numeric_cast<unsigned int>(reshapedDimensions.size()),
327 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);
388 outPadHead = boost::numeric_cast<uint32_t>(padHead);
389 outPadTail = boost::numeric_cast<uint32_t>(padTail);
390}
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);
400 outPadHead = boost::numeric_cast<uint32_t>(padHead);
401 outPadTail = boost::numeric_cast<uint32_t>(padTail);
402}
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,
1403 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001404{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001405 using HalOperand = typename HalPolicy::Operand;
1406
1407 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001408 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1409 {
1410 return false;
1411 }
1412
1413 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001414 if (overrideOutputInfo == nullptr)
1415 {
1416 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1417 }
1418 else
1419 {
1420 outputSlot.SetTensorInfo(*overrideOutputInfo);
1421 }
1422
Finn Williamsa4983ce2020-07-23 12:55:12 +01001423 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001424 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001425 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001426 // Type one dynamic tensors require the previous layer's output shape for inference
1427 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1428 {
1429 if(!layer.GetInputSlot(inputSlotIndex).GetConnection())
1430 {
1431 return false;
1432 }
1433 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001434 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001435 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001436 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001437 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1438
Sadik Armagandbda4b72020-09-03 11:33:07 +01001439 if(!isSupported)
1440 {
1441 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1442 {
1443 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1444 }
1445 return false;
1446 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001447 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001448
Finn Williamsa4983ce2020-07-23 12:55:12 +01001449 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1450 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1451
Mike Kellyb5fdf382019-06-11 16:35:25 +01001452 return true;
1453}
1454
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001455template<typename HalPolicy,
1456 typename HalOperation = typename HalPolicy::Operation,
1457 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001458armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1459 uint32_t inputIndex,
1460 const HalModel& model,
1461 ConversionData& data)
1462{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001463 using HalOperand = typename HalPolicy::Operand;
1464
1465 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001466 if (!operand)
1467 {
1468 return armnn::DataLayout::NHWC;
1469 }
1470
1471 if (!IsBool(*operand))
1472 {
1473 return armnn::DataLayout::NHWC;
1474 }
1475
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001476 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001477 if (!valueAddress)
1478 {
1479 return armnn::DataLayout::NHWC;
1480 }
1481
1482 if (*(static_cast<const bool*>(valueAddress)))
1483 {
1484 return armnn::DataLayout::NCHW;
1485 }
1486 else
1487 {
1488 return armnn::DataLayout::NHWC;
1489 }
1490}
1491
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001492template<typename HalPolicy,
1493 typename HalOperation = typename HalPolicy::Operation,
1494 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001495bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1496 uint32_t outputIndex,
1497 armnn::IConnectableLayer& layer,
1498 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001499 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001500 const armnn::TensorInfo* overrideOutputInfo = nullptr,
1501 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001502{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001503 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1504 outputIndex,
1505 layer,
1506 outputIndex,
1507 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001508 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001509 overrideOutputInfo,
1510 validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001511}
1512
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001513template<typename HalPolicy,
1514 typename HalOperation = typename HalPolicy::Operation,
1515 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001516bool ConvertToActivation(const HalOperation& operation,
1517 const char* operationName,
1518 const armnn::ActivationDescriptor& activationDesc,
1519 const HalModel& model,
1520 ConversionData& data)
1521{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001522 using HalOperand = typename HalPolicy::Operand;
1523
1524 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001525 if (!input.IsValid())
1526 {
1527 return Fail("%s: Input 0 is invalid", operationName);
1528 }
1529
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001530 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001531 if (!outputOperand)
1532 {
1533 return false;
1534 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001535
1536 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001537
1538 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001539
1540 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1541 {
1542 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1543 IsActivationSupported,
1544 data.m_Backends,
1545 isSupported,
1546 input.GetTensorInfo(),
1547 outInfo,
1548 activationDesc);
1549 };
1550
1551 if(IsDynamicTensor(outInfo))
1552 {
1553 isSupported = AreDynamicTensorsSupported();
1554 }
1555 else
1556 {
1557 validateFunc(outInfo, isSupported);
1558 }
1559
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001560 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001561 {
1562 return false;
1563 }
1564
1565 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001566 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001567 input.Connect(layer->GetInputSlot(0));
1568
Finn Williamsa4983ce2020-07-23 12:55:12 +01001569 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001570}
1571
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001572template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001573 typename HalOperation = typename HalPolicy::Operation,
1574 typename HalModel = typename HalPolicy::Model>
1575bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1576{
1577 armnn::ActivationDescriptor desc;
1578 desc.m_Function = armnn::ActivationFunction::ReLu;
1579
1580 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1581}
1582
1583template<typename HalPolicy,
1584 typename HalOperation = typename HalPolicy::Operation,
1585 typename HalModel = typename HalPolicy::Model>
1586bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1587{
1588 armnn::ActivationDescriptor desc;
1589 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1590 desc.m_A = 1.0f;
1591 desc.m_B = -1.0f;
1592
1593 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1594}
1595
1596template<typename HalPolicy,
1597 typename HalOperation = typename HalPolicy::Operation,
1598 typename HalModel = typename HalPolicy::Model>
1599bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1600{
1601 armnn::ActivationDescriptor desc;
1602 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1603 desc.m_A = 6.0f;
1604
1605 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1606}
1607
1608template<typename HalPolicy,
1609 typename HalOperation = typename HalPolicy::Operation,
1610 typename HalModel = typename HalPolicy::Model>
1611bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1612{
1613 armnn::ActivationDescriptor desc;
1614 desc.m_Function = armnn::ActivationFunction::TanH;
1615 desc.m_A = 1.0f; // android nn does not support tanH parameters
1616 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1617
1618 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1619}
1620
1621template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001622 typename HalOperation = typename HalPolicy::Operation,
1623 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001624bool ConvertPaddings(const HalOperation& operation,
1625 const HalModel& model,
1626 ConversionData& data,
1627 unsigned int rank,
1628 armnn::PadDescriptor& padDescriptor)
1629{
1630 using HalOperand = typename HalPolicy::Operand;
1631
1632 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1633 if (!paddingsOperand)
1634 {
1635 return Fail("%s: Could not read paddings operand", __func__);
1636 }
1637
1638 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1639 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1640 {
1641 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1642 }
1643
1644 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001645 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1646 {
1647 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1648 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001649
1650 // add padding for each dimension of input tensor.
1651 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1652 {
1653 int paddingBeforeInput = paddings[i];
1654 int paddingAfterInput = paddings[i + 1];
1655
1656 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1657 {
1658 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1659 }
1660
1661 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1662 }
1663
1664 return true;
1665}
1666
1667template<typename HalPolicy,
1668 typename HalOperation = typename HalPolicy::Operation,
1669 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001670bool ConvertPooling2d(const HalOperation& operation,
1671 const char* operationName,
1672 armnn::PoolingAlgorithm poolType,
1673 const HalModel& model,
1674 ConversionData& data)
1675{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001676 using HalOperand = typename HalPolicy::Operand;
1677 using HalOperandType = typename HalPolicy::OperandType;
1678
1679 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001680 if (!input.IsValid())
1681 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001682 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001683 }
1684
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001685 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001686 if (!output)
1687 {
1688 return Fail("%s: Could not read output 0", __func__);
1689 }
1690
1691 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1692 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1693
arovir01b0717b52018-09-05 17:03:25 +01001694 armnn::Pooling2dDescriptor desc;
1695 desc.m_PoolType = poolType;
1696 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001697 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001698
1699 ActivationFn activation;
1700
Sadik Armagan15d63e22019-07-26 16:59:35 +01001701 auto inputSize = operation.inputs.size();
1702
1703 if (inputSize >= 10)
1704 {
1705 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1706 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1707 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1708 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1709 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1710 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1711 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1712 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1713 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1714 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1715 {
1716 return Fail("%s: Operation has invalid inputs", operationName);
1717 }
1718
Kevin May42477c12020-03-26 13:34:14 +00001719 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001720 {
1721 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1722 }
1723 }
1724 else
arovir01b0717b52018-09-05 17:03:25 +01001725 {
1726 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1727 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001728 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1729 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1730 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1731 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1732 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1733 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001734 {
1735 return Fail("%s: Operation has invalid inputs", operationName);
1736 }
1737
Kevin May42477c12020-03-26 13:34:14 +00001738 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001739 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001740 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001741 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001742
1743 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1744 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1745 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1746
1747 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1748 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001749 }
1750
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001751 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001752
1753 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1754 {
1755 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1756 IsPooling2dSupported,
1757 data.m_Backends,
1758 isSupported,
1759 inputInfo,
1760 outputInfo,
1761 desc);
1762
1763 };
1764
1765 if(IsDynamicTensor(outputInfo))
1766 {
1767 isSupported = AreDynamicTensorsSupported();
1768 }
1769 else
1770 {
1771 validateFunc(outputInfo, isSupported);
1772 }
1773
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001774 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001775 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001776 return false;
arovir01b0717b52018-09-05 17:03:25 +01001777 }
arovir01b0717b52018-09-05 17:03:25 +01001778
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001779 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1780 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001781 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001782 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001783 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001784
1785 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1786 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001787 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001788 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001789 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001790
1791 input.Connect(pooling2dLayer->GetInputSlot(0));
1792
Finn Williamsa4983ce2020-07-23 12:55:12 +01001793 if (!isSupported)
1794 {
1795 return false;
1796 }
1797
1798 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001799}
1800
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001801template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001802 typename HalOperation = typename HalPolicy::Operation,
1803 typename HalModel = typename HalPolicy::Model>
1804bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001805{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001806 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001807
1808 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1809 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1810
1811 if (!input0.IsValid() || !input1.IsValid())
1812 {
1813 return Fail("%s: Operation has invalid inputs", __func__);
1814 }
1815
1816 // The FuseActivation parameter is always the input index 2
1817 // and it should be optional
1818 ActivationFn activationFunction;
1819 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1820 {
1821 return Fail("%s: Operation has invalid inputs", __func__);
1822 }
1823
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001824 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001825 if (!outputOperand)
1826 {
1827 return false;
1828 }
1829
1830 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1831 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1832
1833 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001834
1835 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001836 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1837 {
1838 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1839 IsAdditionSupported,
1840 data.m_Backends,
1841 isSupported,
1842 inputInfo0,
1843 inputInfo1,
1844 outputInfo);
1845 };
1846
1847 if(!IsDynamicTensor(outputInfo))
1848 {
1849 validateFunc(outputInfo, isSupported);
1850 }
1851 else
1852 {
1853 isSupported = AreDynamicTensorsSupported();
1854 }
1855
Mike Kelly46272802019-08-14 17:00:48 +01001856 if (!isSupported)
1857 {
1858 return false;
1859 }
1860
1861 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
1862 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
1863
1864 if (endLayer != nullptr)
1865 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00001866 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01001867 if (!isReshapeSupported)
1868 {
1869 return false;
1870 }
1871
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001872 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01001873 }
1874 else
1875 {
1876 return Fail("%s: ProcessActivation failed", __func__);
1877 }
1878}
1879
1880template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001881 typename HalOperation = typename HalPolicy::Operation,
1882 typename HalModel = typename HalPolicy::Model>
1883bool ConvertArgMinMax(const HalOperation& operation,
1884 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001885 ConversionData& data,
1886 armnn::ArgMinMaxFunction argMinMaxFunction)
1887{
1888 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1889
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001890 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001891 using HalOperandType = typename HalPolicy::OperandType;
1892
1893 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1894
1895 if (!input0.IsValid())
1896 {
1897 return Fail("%s: Operation has invalid inputs", __func__);
1898 }
1899
1900 int32_t axis;
1901 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1902 {
1903 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1904 }
1905
1906 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1907 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1908
1909 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1910 {
1911 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1912 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1913 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1914 return Fail("%s: Axis must be in range [-n, n)", __func__);
1915 }
1916
1917 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1918 if (!output)
1919 {
1920 return Fail("%s: Could not read output 0", __func__);
1921 }
1922
1923 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1924
1925 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001926
1927 armnn::ArgMinMaxDescriptor descriptor;
1928 descriptor.m_Function = argMinMaxFunction;
1929 descriptor.m_Axis = axis;
1930
1931 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001932
1933 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1934 {
1935 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1936 IsArgMinMaxSupported,
1937 data.m_Backends,
1938 isSupported,
1939 inputInfo0,
1940 outputInfo,
1941 descriptor);
1942 };
1943
1944 if(IsDynamicTensor(outputInfo))
1945 {
1946 isSupported = AreDynamicTensorsSupported();
1947 }
1948 else
1949 {
1950 validateFunc(outputInfo, isSupported);
1951 }
1952
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001953 if (!isSupported)
1954 {
1955 return false;
1956 }
1957
1958 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1959 assert(layer != nullptr);
1960
1961 input0.Connect(layer->GetInputSlot(0));
1962
Finn Williamsa4983ce2020-07-23 12:55:12 +01001963 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001964}
1965
1966template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001967 typename HalOperation = typename HalPolicy::Operation,
1968 typename HalModel = typename HalPolicy::Model>
1969bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001970{
Keith Davis6e4081f2020-09-03 13:17:21 +01001971 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001972 using HalOperandType = typename HalPolicy::OperandType;
1973
1974 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1975 if (operation.inputs.size() <= 1)
1976 {
1977 return Fail("%s: Operation has insufficient arguments", __func__);
1978 }
1979
1980 // Get inputs and outputs
1981 const std::size_t numInputTensors = operation.inputs.size() - 1;
1982
1983 int32_t concatDim;
1984 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1985 {
1986 return Fail("%s: Operation has invalid inputs", __func__);
1987 }
1988
1989 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1990 if (!outputOperand)
1991 {
1992 return Fail("%s: Operation has no outputs", __func__);
1993 }
1994
Keith Davis6e4081f2020-09-03 13:17:21 +01001995 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
1996 armnn::TensorShape outputShape = outputInfo.GetShape();
1997 const bool isDynamicTensor = IsDynamicTensor(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01001998 //
1999 // handle negative concat dims along the lines of tensorflow as described here:
2000 // https://www.tensorflow.org/api_docs/python/tf/concat
2001 // "negative axis refers to axis + rank(values)-th dimension"
2002 //
2003 if (concatDim < 0)
2004 {
2005 concatDim += outputShape.GetNumDimensions();
2006 }
2007
2008 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2009 {
2010 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2011 }
2012
2013 std::vector<LayerInputHandle> inputHandles;
2014 std::vector<armnn::TensorShape> inputShapes;
2015
2016 inputHandles.reserve(numInputTensors);
2017 inputShapes.reserve(numInputTensors);
2018
Keith Davis6e4081f2020-09-03 13:17:21 +01002019 bool inputsHaveBeenReshaped = false;
2020 unsigned int tensorDimensionsAdded = 0;
Mike Kellyb8805202019-07-31 17:25:43 +01002021 for (uint32_t i = 0; i < numInputTensors; ++i)
2022 {
2023 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2024 if (!operand)
2025 {
2026 return Fail("%s: Operation has invalid inputs", __func__);
2027 }
2028
Teresa Charlin3b959602019-10-31 17:05:47 +00002029 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2030 if (!operandInputHandle.IsValid())
2031 {
2032 return Fail("%s: Operation has invalid inputs", __func__);
2033 }
Mike Kellyb8805202019-07-31 17:25:43 +01002034
Keith Davis6e4081f2020-09-03 13:17:21 +01002035 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002036 if (operandShape.GetNumDimensions() == 0)
2037 {
2038 return Fail("%s: Operands with rank 0 are not supported", __func__);
2039 }
2040
2041 if (RequiresReshape(operandShape))
2042 {
2043 inputsHaveBeenReshaped = true;
2044
2045 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2046
2047 // Expand the tensor to three dimensions
2048 if (operandShape.GetNumDimensions() == 2)
2049 {
2050 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2051 tensorDimensionsAdded = 1;
2052 }
2053 else
2054 {
2055 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2056 tensorDimensionsAdded = 2;
2057 }
2058
Kevin Mayaed08ac2019-12-12 16:33:31 +00002059 armnn::ReshapeDescriptor reshapeDescriptor;
2060 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2061
2062 bool isSupported = false;
2063 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2064 IsReshapeSupported,
2065 data.m_Backends,
2066 isSupported,
2067 operandInputHandle.GetTensorInfo(),
2068 reshapeInfo,
2069 reshapeDescriptor);
Keith Davis6e4081f2020-09-03 13:17:21 +01002070
Kevin Mayaed08ac2019-12-12 16:33:31 +00002071 if (!isSupported)
2072 {
2073 return false;
2074 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002075 armnn::IConnectableLayer& newReshape = AddReshapeLayer(*data.m_Network, operandInputHandle, reshapeInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002076
2077 // Point to the reshape operation rather then the input operation
Keith Davis6e4081f2020-09-03 13:17:21 +01002078 operandShape = reshapeInfo.GetShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002079 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2080 }
2081
2082 inputShapes.emplace_back(operandShape);
2083 inputHandles.emplace_back(operandInputHandle);
2084
2085 if (!inputHandles.back().IsValid())
2086 {
2087 return Fail("%s: Operation has invalid inputs", __func__);
2088 }
2089 }
2090
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002091 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002092
2093 if (inputsHaveBeenReshaped)
2094 {
2095 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2096 concatDim += tensorDimensionsAdded;
2097
2098 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2099 if (tensorDimensionsAdded == 1)
2100 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002101 if (IsDynamicTensor(outputInfo))
2102 {
2103 outputShape = armnn::TensorShape({1, 0, 0}, {true, false, false});
2104 }
2105 else
2106 {
2107 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2108 }
Mike Kellyb8805202019-07-31 17:25:43 +01002109 }
2110 else if (tensorDimensionsAdded == 2)
2111 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002112 if (IsDynamicTensor(outputInfo))
2113 {
2114 outputShape = armnn::TensorShape({1, 1, 0}, {true, true, false});
2115 }
2116 else
2117 {
2118 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2119 }
Mike Kellyb8805202019-07-31 17:25:43 +01002120 }
2121 }
2122
2123 // Check if permutations is required and get the pair of permutations required for the concatenation.
2124 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2125 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
Keith Davis6e4081f2020-09-03 13:17:21 +01002126 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
Mike Kellyb8805202019-07-31 17:25:43 +01002127
Keith Davis6e4081f2020-09-03 13:17:21 +01002128 bool needPermute = CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(),
2129 concatDim,
2130 permutationPair);
Mike Kellyb8805202019-07-31 17:25:43 +01002131
Keith Davis6e4081f2020-09-03 13:17:21 +01002132 // Only relevant to static tensors as dynamic output tensors will be transposed as a result of inferring from input
2133 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002134 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002135 if (needPermute)
2136 {
2137 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
2138 }
2139
2140 outputInfo.SetShape(outputShape);
Mike Kellyb8805202019-07-31 17:25:43 +01002141 }
Mike Kellyb8805202019-07-31 17:25:43 +01002142 // this is no-op for identity swizzles, otherwise it replaces both
2143 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002144 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002145 {
2146 return false;
2147 }
Mike Kellyb8805202019-07-31 17:25:43 +01002148
2149 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2150 armnn::OriginsDescriptor concatDescriptor;
2151
2152 try
2153 {
2154 // The concat descriptor is always created across the only supported concat dimension
2155 // 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 +01002156 concatDescriptor = armnn::CreateDescriptorForConcatenation(inputShapes.begin(),
2157 inputShapes.end(),
2158 concatDim);
2159 } catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002160 {
2161 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2162 }
2163
2164 // Validate the output shape is correct given the input shapes based on the
2165 // 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 +01002166 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002167 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002168 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2169 {
2170 return Fail("%s: Error validating the output shape for concat", __func__);
2171 }
Mike Kellyb8805202019-07-31 17:25:43 +01002172 }
2173
2174 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2175 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
Keith Davis6e4081f2020-09-03 13:17:21 +01002176 [](const LayerInputHandle& h)->const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
Mike Kellyb8805202019-07-31 17:25:43 +01002177
Keith Davis6e4081f2020-09-03 13:17:21 +01002178 bool isSupported = false;
2179 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported){
2180 FORWARD_LAYER_SUPPORT_FUNC(__func__, IsConcatSupported, data.m_Backends, isSupported, inputTensorInfos,
2181 outputInfo, concatDescriptor);
2182 };
2183
2184 if (!isDynamicTensor)
2185 {
2186 validateFunc(outputInfo, isSupported);
2187 }
2188 else
2189 {
2190 isSupported = AreDynamicTensorsSupported();
2191 }
2192
Mike Kellyb8805202019-07-31 17:25:43 +01002193 if (!isSupported)
2194 {
2195 return false;
2196 }
2197
2198 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2199 assert(layer != nullptr);
2200 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002201 // Connect inputs to the layer
2202 const int numInputSlots = layer->GetNumInputSlots();
2203 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2204 for (int i = 0; i < numInputSlots; ++i)
2205 {
2206 // connect the input directly to the merge (concat) layer
2207 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2208 }
2209
Keith Davis6e4081f2020-09-03 13:17:21 +01002210 // Transpose the output shape
2211 auto transposeOutputShape = [&](){
Mike Kelly4a956582020-02-28 10:32:09 +00002212 armnn::TransposeDescriptor transposeDesc;
2213 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002214 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2215 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2216 permutationPair.second);
Keith Davis6e4081f2020-09-03 13:17:21 +01002217 isSupported = false;
Kevin Mayaed08ac2019-12-12 16:33:31 +00002218 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002219 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002220 data.m_Backends,
2221 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002222 inputTransposeInfo,
2223 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002224 transposeDesc);
Keith Davis6e4081f2020-09-03 13:17:21 +01002225
Kevin Mayaed08ac2019-12-12 16:33:31 +00002226 if (!isSupported)
2227 {
2228 return false;
2229 }
Mike Kellyb8805202019-07-31 17:25:43 +01002230 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Keith Davis6e4081f2020-09-03 13:17:21 +01002231 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network, layer->GetOutputSlot(0),
Mike Kelly4a956582020-02-28 10:32:09 +00002232 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002233 layer = &deswizzleLayer;
Keith Davis6e4081f2020-09-03 13:17:21 +01002234
2235 return true;
2236 };
2237
2238 if (needPermute && !isDynamicTensor)
2239 {
2240 transposeOutputShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002241 }
2242
2243 if (inputsHaveBeenReshaped)
2244 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002245 if (isDynamicTensor)
2246 {
2247 // Infer the output shapes of concat if outputs are type 1 dynamic
2248 layer->GetOutputSlot(0).IsTensorInfoSet();
2249 if (!ValidateConcatOutputShape(inputShapes,
2250 layer->GetOutputSlot(0).GetTensorInfo().GetShape(),
2251 concatDim))
2252 {
2253 return Fail("%s: Error validating the output shape for concat", __func__);
2254 }
2255 transposeOutputShape();
2256 }
2257
Mike Kellyb8805202019-07-31 17:25:43 +01002258 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
2259
2260 // Undo the reshape knowing the amount of dimensions added
2261 if (tensorDimensionsAdded == 1)
2262 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002263 afterConcatInfo.SetShape(
2264 armnn::TensorShape({afterConcatInfo.GetShape()[1], afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002265 }
2266 else if (tensorDimensionsAdded == 2)
2267 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002268 afterConcatInfo.SetShape(armnn::TensorShape({afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002269 }
2270
Kevin Mayaed08ac2019-12-12 16:33:31 +00002271 armnn::ReshapeDescriptor reshapeDescriptor;
2272 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
Keith Davis6e4081f2020-09-03 13:17:21 +01002273 armnn::TensorInfo concatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Kevin Mayaed08ac2019-12-12 16:33:31 +00002274
Keith Davis6e4081f2020-09-03 13:17:21 +01002275 isSupported = false;
2276 auto validateReshapeFunc = [&](const armnn::TensorInfo& afterConcatInfo, bool& isSupported){
2277 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2278 IsReshapeSupported,
2279 data.m_Backends,
2280 isSupported,
2281 concatInfo,
2282 afterConcatInfo,
2283 reshapeDescriptor);
2284 };
2285
2286 if (!IsDynamicTensor(afterConcatInfo))
2287 {
2288 validateReshapeFunc(afterConcatInfo, isSupported);
2289 }
2290 else
2291 {
2292 isSupported = AreDynamicTensorsSupported();
2293 }
2294
Kevin Mayaed08ac2019-12-12 16:33:31 +00002295 if (!isSupported)
2296 {
2297 return false;
2298 }
2299
Keith Davis6e4081f2020-09-03 13:17:21 +01002300 layer = &AddReshapeLayer(*data.m_Network, layer->GetOutputSlot(0), afterConcatInfo);
2301 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
2302 0,
2303 *layer,
2304 model,
2305 data,
2306 nullptr,
2307 validateReshapeFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002308 }
2309
Keith Davis6e4081f2020-09-03 13:17:21 +01002310 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002311}
2312
2313template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002314 typename HalOperation = typename HalPolicy::Operation,
2315 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002316bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2317{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002318 using HalOperand = typename HalPolicy::Operand;
2319 using HalOperandType = typename HalPolicy::OperandType;
2320
2321 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002322 if (!input.IsValid())
2323 {
2324 return Fail("%s: Operation has invalid inputs", __func__);
2325 }
2326
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002327 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002328 if (!output)
2329 {
2330 return Fail("%s: Could not read output 0", __func__);
2331 }
2332
2333 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002334 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002335
2336 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002337 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2338 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002339
2340 if (!weightsPin.IsValid() || !biasPin.IsValid())
2341 {
2342 return Fail("%s: Operation has invalid inputs", __func__);
2343 }
2344
2345 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002346 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002347 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2348
2349 armnn::Convolution2dDescriptor desc;
2350 desc.m_DataLayout = armnn::DataLayout::NHWC;
2351 ActivationFn activation;
2352
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002353 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002354 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002355 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2356 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2357 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2358 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2359 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2360 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002361 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002362 {
2363 return Fail("%s: Operation has invalid inputs", __func__);
2364 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002365 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002366 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002367 {
2368 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002369 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2370 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2371 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002372 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002373 {
2374 return Fail("%s: Operation has invalid inputs", __func__);
2375 }
2376
2377 const uint32_t kernelX = weights.GetShape()[2];
2378 const uint32_t kernelY = weights.GetShape()[1];
2379 const uint32_t inputX = inputInfo.GetShape()[2];
2380 const uint32_t inputY = inputInfo.GetShape()[1];
2381
2382 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2383 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002384 }
2385 else
2386 {
2387 return Fail("%s: Unsupported number of operation inputs", __func__);
2388 }
2389
2390 desc.m_BiasEnabled = true;
2391 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2392
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002393 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002394 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2395 {
2396 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2397 IsConvolution2dSupported,
2398 data.m_Backends,
2399 isSupported,
2400 inputInfo,
2401 outputInfo,
2402 desc,
2403 weights.GetInfo(),
2404 biases);
2405 };
2406
2407 if(!IsDynamicTensor(outputInfo))
2408 {
2409 validateFunc(outputInfo, isSupported);
2410 }
2411 else
2412 {
2413 isSupported = AreDynamicTensorsSupported();
2414 }
2415
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002416 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002417 {
2418 return false;
2419 }
2420
2421 armnn::IConnectableLayer* startLayer =
2422 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2423
2424 if (!startLayer)
2425 {
2426 return Fail("%s: AddConvolution2dLayer failed", __func__);
2427 }
2428
2429 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2430
2431 if (!endLayer)
2432 {
2433 return Fail("%s: ProcessActivation failed", __func__);
2434 }
2435
2436 input.Connect(startLayer->GetInputSlot(0));
2437
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002438 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002439}
2440
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002441template<typename HalPolicy,
2442 typename HalOperation = typename HalPolicy::Operation,
2443 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002444bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2445{
2446 using HalOperand = typename HalPolicy::Operand;
2447 using HalOperandType = typename HalPolicy::OperandType;
2448
2449 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2450 if (!input.IsValid() )
2451 {
2452 return Fail("%s: Operation has invalid inputs", __func__);
2453 }
2454
2455 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2456 unsigned int rank = inputInfo.GetNumDimensions();
2457 if (rank != 4)
2458 {
2459 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2460 }
2461
2462 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2463 if (!output)
2464 {
2465 return Fail("%s: Could not read output 0", __func__);
2466 }
2467
2468 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002469
2470 armnn::DepthToSpaceDescriptor descriptor;
2471
2472 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2473 if (descriptor.m_BlockSize <= 1)
2474 {
2475 return Fail("%s: Block size must be at least 1 in all dimensions");
2476 }
2477
2478 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002479 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002480 {
2481 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2482 }
2483
2484 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002485 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2486 {
2487 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2488 IsDepthToSpaceSupported,
2489 data.m_Backends,
2490 isSupported,
2491 inputInfo,
2492 outputInfo,
2493 descriptor);
2494 };
2495
2496 if(!IsDynamicTensor(outputInfo))
2497 {
2498 validateFunc(outputInfo, isSupported);
2499 }
2500 else
2501 {
2502 isSupported = AreDynamicTensorsSupported();
2503 }
2504
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002505 if (!isSupported)
2506 {
2507 return false;
2508 }
2509
2510 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2511 assert(layer != nullptr);
2512 input.Connect(layer->GetInputSlot(0));
2513
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002514 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002515}
2516
2517template<typename HalPolicy,
2518 typename HalOperation = typename HalPolicy::Operation,
2519 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002520bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2521{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002522 using HalOperand = typename HalPolicy::Operand;
2523 using HalOperandType = typename HalPolicy::OperandType;
2524
2525 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002526
2527 if (!input.IsValid())
2528 {
2529 return Fail("%s: Operation has invalid inputs", __func__);
2530 }
2531
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002532 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002533
2534 if (!output)
2535 {
2536 return Fail("%s: Could not read output 0", __func__);
2537 }
2538
2539 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002540 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002541
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002542 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002543 // 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 +01002544 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002545
2546 if (weightsOperand == nullptr)
2547 {
2548 return Fail("%s: Operand is invalid", __func__);
2549 }
2550 armnn::DepthwiseConvolution2dDescriptor desc;
2551 desc.m_DataLayout = armnn::DataLayout::NHWC;
2552
Mike Kellyb5fdf382019-06-11 16:35:25 +01002553 // Reinterpret weight data as [ H, W, I, M ]
2554 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2555 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002556 inputInfo.GetShape()[3],
2557 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002558
2559 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2560 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2561
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002562 const ConstTensorPin weightsPin =
2563 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2564 1,
2565 model,
2566 data,
2567 HWIMToMIHW,
2568 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002569
2570 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002571 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002572
2573 if (!weightsPin.IsValid() || !biasPin.IsValid())
2574 {
2575 return Fail("%s: Operation has invalid inputs", __func__);
2576 }
2577
2578 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2579 armnn::ConstTensor bias = biasPin.GetConstTensor();
2580 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2581
2582 ActivationFn activation;
2583
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002584 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002585 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002586 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2587 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2588 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2589 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2590 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2591 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002592 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002593 {
2594 return Fail("%s: Operation has invalid inputs", __func__);
2595 }
2596 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002597 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002598 {
2599 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002600 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2601 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2602 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002603 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002604 {
2605 return Fail("%s: Operation has invalid inputs", __func__);
2606 }
2607
2608 const uint32_t kernelX = weights.GetShape()[3];
2609 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002610 const uint32_t inputX = inputInfo.GetShape()[2];
2611 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002612
2613 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2614 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2615 }
2616 else
2617 {
2618 return Fail("%s: Unsupported number of operation inputs", __func__);
2619 }
2620
2621 desc.m_BiasEnabled = true;
2622 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2623
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002624 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002625 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2626 {
2627 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2628 IsDepthwiseConvolutionSupported,
2629 data.m_Backends,
2630 isSupported,
2631 inputInfo,
2632 outputInfo,
2633 desc,
2634 weights.GetInfo(),
2635 biases);
2636 };
2637
2638 if(!IsDynamicTensor(outputInfo))
2639 {
2640 validateFunc(outputInfo, isSupported);
2641 }
2642 else
2643 {
2644 isSupported = AreDynamicTensorsSupported();
2645 }
2646
2647
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002648 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002649 {
2650 return false;
2651 }
2652
2653 armnn::IConnectableLayer* startLayer =
2654 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2655 if (!startLayer)
2656 {
2657 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2658 }
2659
2660 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2661 if (!endLayer)
2662 {
2663 return Fail("%s: ProcessActivation failed", __func__);
2664 }
2665
2666 input.Connect(startLayer->GetInputSlot(0));
2667
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002668 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01002669}
2670
Mike Kelly3c673942019-07-25 09:26:06 +01002671template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002672 typename HalOperation = typename HalPolicy::Operation,
2673 typename HalModel = typename HalPolicy::Model>
2674bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002675{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002676 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002677
2678 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2679 if (!input.IsValid())
2680 {
2681 return Fail("%s: Operation has invalid input", __func__);
2682 }
2683
Sadik Armagan98c0f662019-11-21 15:54:36 +00002684 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2685 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2686 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2687 {
2688 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2689 }
2690
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002691 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002692 if (!outputOperand)
2693 {
2694 return Fail("%s: Operation has invalid outputs", __func__);
2695 }
2696
2697 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002698
2699 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002700 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2701 {
2702 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2703 IsDequantizeSupported,
2704 data.m_Backends,
2705 isSupported,
2706 inputInfo,
2707 outputInfo);
2708 };
2709
2710 if(IsDynamicTensor(outputInfo))
2711 {
2712 isSupported = AreDynamicTensorsSupported();
2713 }
2714 else
2715 {
2716 validateFunc(outputInfo, isSupported);
2717 }
2718
Mike Kelly46272802019-08-14 17:00:48 +01002719 if (!isSupported)
2720 {
2721 return false;
2722 }
2723
2724 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2725 assert(layer != nullptr);
2726 input.Connect(layer->GetInputSlot(0));
2727
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002728 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002729}
2730
2731template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002732 typename HalOperation = typename HalPolicy::Operation,
2733 typename HalModel = typename HalPolicy::Model>
2734bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002735{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002736 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002737
2738 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2739 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2740
2741 if (!input0.IsValid() || !input1.IsValid())
2742 {
2743 return Fail("%s: Operation has invalid inputs", __func__);
2744 }
2745
2746 // The FuseActivation parameter is always the input index 2
2747 // and it should be optional
2748 ActivationFn activationFunction;
2749 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2750 {
2751 return Fail("%s: Operation has invalid inputs", __func__);
2752 }
2753
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002754 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002755 if (!output)
2756 {
2757 return Fail("%s: Could not read output 0", __func__);
2758 }
2759
2760 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002761
2762 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002763 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2764 {
2765 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2766 IsDivisionSupported,
2767 data.m_Backends,
2768 isSupported,
2769 input0.GetTensorInfo(),
2770 input1.GetTensorInfo(),
2771 outputInfo);
2772 };
2773
2774 if(!IsDynamicTensor(outputInfo))
2775 {
2776 validateFunc(outputInfo, isSupported);
2777 }
2778 else
2779 {
2780 isSupported = AreDynamicTensorsSupported();
2781 }
2782
Mike Kelly46272802019-08-14 17:00:48 +01002783 if (!isSupported)
2784 {
2785 return false;
2786 }
2787
2788 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
2789 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2790
2791 if (endLayer)
2792 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00002793 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01002794 if (!isReshapeSupported)
2795 {
2796 return false;
2797 }
2798
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002799 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002800 }
2801 return Fail("%s: ProcessActivation failed", __func__);
2802}
2803
2804template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002805 typename HalOperation = typename HalPolicy::Operation,
2806 typename HalModel = typename HalPolicy::Model>
2807bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002808{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002809 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002810
2811 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2812 if (!input.IsValid())
2813 {
2814 return Fail("%s: Operation has invalid inputs", __func__);
2815 }
2816
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002817 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002818 if (!outputOperand)
2819 {
2820 return Fail("%s: Operation has invalid outputs", __func__);
2821 }
2822
2823 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002824
2825 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002826 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2827 {
2828 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2829 IsFloorSupported,
2830 data.m_Backends,
2831 isSupported,
2832 input.GetTensorInfo(),
2833 outputInfo);
2834 };
2835
2836 if(!IsDynamicTensor(outputInfo))
2837 {
2838 validateFunc(outputInfo, isSupported);
2839 }
2840 else
2841 {
2842 isSupported = AreDynamicTensorsSupported();
2843 }
2844
Mike Kelly46272802019-08-14 17:00:48 +01002845 if (!isSupported)
2846 {
2847 return false;
2848 }
2849
2850 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2851 assert(layer != nullptr);
2852 input.Connect(layer->GetInputSlot(0));
2853
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002854 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002855}
2856
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002857inline bool IsQSymm8(const V1_0::Operand&)
2858{
2859 return false;
2860}
2861
Kevin May42477c12020-03-26 13:34:14 +00002862#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002863
2864inline bool IsQSymm8(const V1_2::Operand& operand)
2865{
2866 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2867}
2868
2869#endif
2870
Kevin May42477c12020-03-26 13:34:14 +00002871#ifdef ARMNN_ANDROID_NN_V1_3
2872
2873inline bool IsQSymm8(const V1_3::Operand& operand)
2874{
2875 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2876}
2877
2878#endif
2879
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002880enum class DequantizeStatus
2881{
2882 SUCCESS,
2883 NOT_REQUIRED,
2884 INVALID_OPERAND
2885};
2886
2887using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2888
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002889template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002890 typename HalOperation = typename HalPolicy::Operation,
2891 typename HalModel = typename HalPolicy::Model>
2892DequantizeResult DequantizeIfRequired(size_t operand_index,
2893 const HalOperation& operation,
2894 const HalModel& model,
2895 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002896{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002897 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002898
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002899 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002900 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002901 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002902 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002903 }
2904
2905 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2906 {
2907 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002908 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002909 }
2910
2911 const size_t weightsInputIndex = operation.inputs[operand_index];
2912
2913 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2914 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002915 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002916 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002917 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002918 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002919 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2920 {
2921 continue;
2922 }
2923
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002924 size_t outOpIndex = weightsInputIndex + 1;
2925 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002926 {
2927 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002928 }
2929
2930 if (outOpIndex != weightsInputIndex)
2931 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002932 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002933 }
2934
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002935 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002936 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002937
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002938 if (!IsQSymm8(*operand))
2939 {
2940 // Only supporting dequantize from QSYMM8 to FLOAT
2941 break;
2942 }
2943
2944 // Allocate a new buffer for the dequantized data and manually dequantize
2945 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2946 if (!startValue)
2947 {
2948 // Failed to get the operand address
2949 break;
2950 }
2951
2952 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2953 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002954 const float quantizationScale = operand->scale;
2955
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002956 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2957 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2958 {
2959 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002960 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002961 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2962 }
2963
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002964 // Construct tensor info for dequantized ConstTensor
2965 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2966 operand->dimensions.data(),
2967 armnn::DataType::Float32);
2968
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002969 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2970 std::move(tensorInfo),
2971 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002972 }
2973
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002974 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002975}
2976
2977template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002978 typename HalOperation = typename HalPolicy::Operation,
2979 typename HalModel = typename HalPolicy::Model>
2980ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2981 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002982 const ConversionData& data,
2983 size_t operandIndex,
2984 bool optional = false)
2985{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002986 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2987
2988 DequantizeStatus status = std::get<3>(dequantized);
2989 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002990 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002991 case DequantizeStatus::INVALID_OPERAND:
2992 {
2993 // return invalid const tensor pin
2994 return ConstTensorPin();
2995 }
2996 case DequantizeStatus::NOT_REQUIRED:
2997 {
2998 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2999 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
3000 }
3001 case DequantizeStatus::SUCCESS:
3002 default:
3003 {
3004 return ConstTensorPin(
3005 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
3006 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003007 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003008}
3009
3010
Mike Kelly46272802019-08-14 17:00:48 +01003011template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003012 typename HalOperation = typename HalPolicy::Operation,
3013 typename HalModel = typename HalPolicy::Model>
3014bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003015{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003016 using HalOperand = typename HalPolicy::Operand;
3017
Mike Kelly46272802019-08-14 17:00:48 +01003018 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3019 if (!input.IsValid())
3020 {
3021 return Fail("%s: Operation has invalid inputs", __func__);
3022 }
3023
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003024 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003025 if (!output)
3026 {
3027 return Fail("%s: Could not read output 0", __func__);
3028 }
3029
3030 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3031 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3032
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003033 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
3034 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003035
3036 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01003037 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003038 return Fail("%s: Operation has invalid weights", __func__);
3039 }
3040
3041 if (!biasPin.IsValid())
3042 {
3043 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003044 }
3045
3046 armnn::ConstTensor weights = weightsPin.GetConstTensor();
3047 armnn::ConstTensor bias = biasPin.GetConstTensor();
3048 armnn::TensorInfo reshapedInfo = inputInfo;
3049
3050 try
3051 {
3052 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003053 }
3054 catch (const std::exception& e)
3055 {
Mike Kelly46272802019-08-14 17:00:48 +01003056 return Fail("%s: %s", __func__, e.what());
3057 }
3058
3059 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
3060 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
3061
3062 ActivationFn activationFunction;
3063 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3064 {
3065 return Fail("%s: Operation has invalid inputs", __func__);
3066 }
3067
3068 armnn::FullyConnectedDescriptor desc;
3069 desc.m_TransposeWeightMatrix = true;
3070 desc.m_BiasEnabled = true;
3071
FinnWilliamsArm7b8d2e62020-01-08 14:57:47 +00003072 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
3073 weights.GetInfo().GetShape(),
3074 outputInfo.GetShape(),
3075 desc.m_TransposeWeightMatrix))
3076 {
3077 return Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3078 }
3079
Mike Kelly46272802019-08-14 17:00:48 +01003080 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003081 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3082 {
3083 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly46272802019-08-14 17:00:48 +01003084 IsFullyConnectedSupported,
3085 data.m_Backends,
3086 isSupported,
3087 reshapedInfo,
3088 outputInfo,
3089 weights.GetInfo(),
3090 bias.GetInfo(),
3091 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003092 };
3093
3094 if(!IsDynamicTensor(outputInfo))
3095 {
3096 validateFunc(outputInfo, isSupported);
3097 }
3098 else
3099 {
3100 isSupported = AreDynamicTensorsSupported();
3101 }
3102
Mike Kelly46272802019-08-14 17:00:48 +01003103 if (!isSupported)
3104 {
3105 return false;
3106 }
3107
3108 armnn::IConnectableLayer* startLayer =
3109 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
3110 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3111
3112 if (endLayer != nullptr)
3113 {
3114 if (inputInfo.GetNumDimensions() > 2U)
3115 {
3116 armnn::ReshapeDescriptor reshapeDescriptor;
3117 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
3118
3119 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3120 assert(reshapeLayer != nullptr);
3121 input.Connect(reshapeLayer->GetInputSlot(0));
3122 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3123 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
3124 }
3125 else
3126 {
3127 input.Connect(startLayer->GetInputSlot(0));
3128 }
3129
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003130 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003131 }
3132 else
3133 {
3134 return Fail("%s: ProcessActivation failed", __func__);
3135 }
3136}
3137
3138template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003139 typename HalOperation = typename HalPolicy::Operation,
3140 typename HalModel = typename HalPolicy::Model>
3141bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003142{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003143 using HalOperand = typename HalPolicy::Operand;
3144
Mike Kelly999e2092019-08-15 10:46:46 +01003145 if (operation.inputs.size() != 1)
3146 {
3147 return Fail("%s: Optional inputs are not supported", __func__);
3148 }
3149
Mike Kelly46272802019-08-14 17:00:48 +01003150 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3151 if (!input.IsValid())
3152 {
3153 return Fail("%s: Operation has invalid inputs", __func__);
3154 }
3155
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003156 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003157 if (!output)
3158 {
3159 return Fail("%s: Could not read output 0", __func__);
3160 }
3161
3162 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3163 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3164
Mike Kelly46272802019-08-14 17:00:48 +01003165 if (outputInfo.GetNumDimensions() != 4u)
3166 {
3167 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3168 }
3169
3170 armnn::L2NormalizationDescriptor desc;
3171 desc.m_DataLayout = armnn::DataLayout::NHWC;
3172
3173 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003174 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3175 {
3176 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3177 IsL2NormalizationSupported,
3178 data.m_Backends,
3179 isSupported,
3180 inputInfo,
3181 outputInfo,
3182 desc);
3183 };
3184
3185 if(!IsDynamicTensor(outputInfo))
3186 {
3187 validateFunc(outputInfo, isSupported);
3188 }
3189 else
3190 {
3191 isSupported = AreDynamicTensorsSupported();
3192 }
3193
Mike Kelly46272802019-08-14 17:00:48 +01003194 if (!isSupported)
3195 {
3196 return false;
3197 }
3198
3199 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3200 assert(layer != nullptr);
3201 input.Connect(layer->GetInputSlot(0));
3202
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003203 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003204}
3205
3206template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003207 typename HalOperation = typename HalPolicy::Operation,
3208 typename HalModel = typename HalPolicy::Model>
3209bool ConvertLocalResponseNormalization(const HalOperation& operation,
3210 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003211 ConversionData& data)
3212{
Mike Kelly999e2092019-08-15 10:46:46 +01003213 if (operation.inputs.size() != 5)
3214 {
3215 return Fail("%s: Optional inputs are not supported", __func__);
3216 }
3217
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003218 using HalOperand = typename HalPolicy::Operand;
3219 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003220
3221 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3222 if (!input.IsValid())
3223 {
3224 return Fail("%s: Operation has invalid inputs", __func__);
3225 }
3226
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003227 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003228 if (!output)
3229 {
3230 return Fail("%s: Could not read output 0", __func__);
3231 }
3232
3233 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3234 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3235
Mike Kelly46272802019-08-14 17:00:48 +01003236 if (outputInfo.GetNumDimensions() != 4u)
3237 {
3238 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3239 }
3240
3241 armnn::NormalizationDescriptor descriptor;
3242 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3243 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3244 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3245
3246 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003247 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003248 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3249 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3250 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3251 {
3252 return Fail("%s: Operation has invalid inputs", __func__);
3253 }
3254
3255 // ArmNN expects normSize to be the full size of the normalization
3256 // window rather than the radius as in AndroidNN.
3257 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3258
3259 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003260 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3261 {
3262 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3263 IsNormalizationSupported,
3264 data.m_Backends,
3265 isSupported,
3266 inputInfo,
3267 outputInfo,
3268 descriptor);
3269 };
3270
3271 if(!IsDynamicTensor(outputInfo))
3272 {
3273 validateFunc(outputInfo, isSupported);
3274 }
3275 else
3276 {
3277 isSupported = AreDynamicTensorsSupported();
3278 }
3279
Mike Kelly46272802019-08-14 17:00:48 +01003280 if (!isSupported)
3281 {
3282 return false;
3283 }
3284
3285
3286 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3287 assert(layer != nullptr);
3288 input.Connect(layer->GetInputSlot(0));
3289
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003290 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003291}
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 ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003297{
Mike Kelly46272802019-08-14 17:00:48 +01003298 armnn::ActivationDescriptor desc;
3299 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3300
3301 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3302}
3303
3304template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003305 typename HalOperation = typename HalPolicy::Operation,
3306 typename HalModel = typename HalPolicy::Model>
3307bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003308{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003309 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003310
3311 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3312 if (!input.IsValid())
3313 {
3314 return Fail("%s: Operation has invalid inputs", __func__);
3315 }
3316
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003317 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003318 if (!output)
3319 {
3320 return Fail("%s: Could not read output 0", __func__);
3321 }
3322
3323 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003324
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003325 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003326 if (!axisOperand)
3327 {
3328 return Fail("%s: Could not read input 1", __func__);
3329 }
3330
3331 std::vector<int32_t> axis;
3332 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3333 {
3334 return Fail("%s: Input 1 has invalid values", __func__);
3335 }
3336
3337 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3338
3339 // Convert the axis to unsigned int and remove duplicates.
3340 unsigned int rank = inputInfo.GetNumDimensions();
3341 std::set<unsigned int> uniqueAxis;
3342 std::transform(axis.begin(), axis.end(),
3343 std::inserter(uniqueAxis, uniqueAxis.begin()),
3344 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3345
3346 // Get the "keep dims" flag.
3347 int32_t keepDims = 0;
3348 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3349 {
3350 return Fail("%s: Could not read input 2", __func__);
3351 }
3352
3353 armnn::MeanDescriptor descriptor;
3354 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3355 descriptor.m_KeepDims = keepDims > 0;
3356
3357 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003358 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3359 {
3360 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3361 IsMeanSupported,
3362 data.m_Backends,
3363 isSupported,
3364 inputInfo,
3365 outputInfo,
3366 descriptor);
3367 };
3368
3369 if(!IsDynamicTensor(outputInfo))
3370 {
3371 validateFunc(outputInfo, isSupported);
3372 }
3373 else
3374 {
3375 isSupported = AreDynamicTensorsSupported();
3376 }
3377
Mike Kelly46272802019-08-14 17:00:48 +01003378 if (!isSupported)
3379 {
3380 return false;
3381 }
3382
3383 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3384 assert(layer != nullptr);
3385 input.Connect(layer->GetInputSlot(0));
3386
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003387 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003388}
3389
3390template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003391 typename HalOperation = typename HalPolicy::Operation,
3392 typename HalModel = typename HalPolicy::Model>
3393bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003394{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003395 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003396
3397 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3398 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3399
3400 if (!input0.IsValid() || !input1.IsValid())
3401 {
3402 return Fail("%s: Operation has invalid inputs", __func__);
3403 }
3404
3405 // The FuseActivation parameter is always the input index 2
3406 // and it should be optional
3407 ActivationFn activationFunction;
3408 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3409 {
3410 return Fail("%s: Operation has invalid inputs", __func__);
3411 }
3412
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003413 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003414
3415 if (outputOperand == nullptr)
3416 {
3417 return false;
3418 }
3419
3420 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003421
3422 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003423 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3424 {
3425 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3426 IsMultiplicationSupported,
3427 data.m_Backends,
3428 isSupported,
3429 input0.GetTensorInfo(),
3430 input1.GetTensorInfo(),
3431 outputInfo);
3432 };
3433
3434 if(!IsDynamicTensor(outputInfo))
3435 {
3436 validateFunc(outputInfo, isSupported);
3437 }
3438 else
3439 {
3440 isSupported = AreDynamicTensorsSupported();
3441 }
3442
Mike Kelly46272802019-08-14 17:00:48 +01003443 if (!isSupported)
3444 {
3445 return false;
3446 }
3447
3448 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
3449 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3450
3451 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3452 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3453
3454 if (endLayer != nullptr)
3455 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003456 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003457 if (!isReshapeSupported)
3458 {
3459 return false;
3460 }
3461
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003462 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003463 }
3464 else
3465 {
3466 return Fail("%s: ProcessActivation failed", __func__);
3467 }
3468}
3469
3470template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003471 typename HalOperation = typename HalPolicy::Operation,
3472 typename HalModel = typename HalPolicy::Model>
3473bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003474{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003475 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003476
Mike Kelly3c673942019-07-25 09:26:06 +01003477 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3478 if (!input.IsValid())
3479 {
3480 return Fail("%s: Operation has invalid inputs", __func__);
3481 }
3482
3483 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3484 unsigned int rank = inputInfo.GetNumDimensions();
3485
3486 armnn::PadDescriptor descriptor;
3487 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3488 {
3489 return Fail("%s: Could not convert paddings", __func__);
3490 }
3491
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003492 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3493 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003494 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3495 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3496 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003497 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003498 {
3499 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3500 }
3501
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003502 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003503 if (!output)
3504 {
3505 return Fail("%s: Could not read output", __func__);
3506 }
3507
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003508 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003509
3510 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003511 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3512 {
3513 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3514 IsPadSupported,
3515 data.m_Backends,
3516 isSupported,
3517 inputInfo,
3518 outputInfo,
3519 descriptor);
3520 };
3521
3522 if(!IsDynamicTensor(outputInfo))
3523 {
3524 validateFunc(outputInfo, isSupported);
3525 }
3526 else
3527 {
3528 isSupported = AreDynamicTensorsSupported();
3529 }
3530
Mike Kelly3c673942019-07-25 09:26:06 +01003531 if (!isSupported)
3532 {
3533 return false;
3534 }
3535
3536 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3537 assert(layer != nullptr);
3538 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003539
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003540 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003541}
3542
Mike Kelly0a879362019-07-29 16:56:31 +01003543template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003544 typename HalOperation = typename HalPolicy::Operation,
3545 typename HalModel = typename HalPolicy::Model>
3546bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003547{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003548 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003549
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003550 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3551 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3552 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003553
3554 if (inputOperand == nullptr
3555 || requestedShapeOperand == nullptr
3556 || outputOperand == nullptr)
3557 {
3558 return Fail("%s: Operation has invalid inputs", __func__);
3559 }
3560
3561 if (requestedShapeOperand->dimensions.size() != 1)
3562 {
3563 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3564 __func__, requestedShapeOperand->dimensions.size());
3565 }
3566
3567 std::vector<int32_t> targetDimensions;
3568 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3569 {
3570 return Fail("%s: Could not read values of input 1", __func__);
3571 }
3572
3573 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3574
3575 Shape requestedShape;
3576 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3577 // function that resolves these values into a fully specified tensor shape.
3578 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3579 {
3580 return Fail("%s: Failed to resolve the requested shape", __func__);
3581 }
3582
Mike Kelly46272802019-08-14 17:00:48 +01003583 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3584 if (!input.IsValid())
3585 {
3586 return Fail("%s: Could not read input 0", __func__);
3587 }
3588
3589 armnn::ReshapeDescriptor reshapeDescriptor;
3590 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3591 requestedShape.dimensions.data());
3592
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003593 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3594
Mike Kelly46272802019-08-14 17:00:48 +01003595 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003596 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3597 {
3598 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3599 IsReshapeSupported,
3600 data.m_Backends,
3601 isSupported,
3602 input.GetTensorInfo(),
3603 outputInfo,
3604 reshapeDescriptor);
3605 };
3606
3607 if(!IsDynamicTensor(outputInfo))
3608 {
3609 validateFunc(outputInfo, isSupported);
3610 }
3611 else
3612 {
3613 isSupported = AreDynamicTensorsSupported();
3614 }
3615
Mike Kelly46272802019-08-14 17:00:48 +01003616 if (!isSupported)
3617 {
3618 return false;
3619 }
3620
3621 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3622 assert(layer != nullptr);
3623 input.Connect(layer->GetInputSlot(0));
3624
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003625 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003626}
3627
3628template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003629 typename HalOperation = typename HalPolicy::Operation,
3630 typename HalModel = typename HalPolicy::Model>
3631bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003632{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003633 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003634
Mike Kelly0a879362019-07-29 16:56:31 +01003635 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3636 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3637
3638 if (!input0.IsValid() || !input1.IsValid())
3639 {
3640 return Fail("%s: Operation has invalid inputs", __func__);
3641 }
3642
3643 // The FuseActivation parameter is always the input index 2
3644 // and it should be optional
3645 ActivationFn activationFunction;
3646 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3647 {
3648 return Fail("%s: Operation has invalid inputs", __func__);
3649 }
3650
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003651 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003652 if (!output)
3653 {
3654 return Fail("%s: Could not read output 0", __func__);
3655 }
3656
3657 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003658
3659 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003660 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3661 {
3662 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3663 IsSubtractionSupported,
3664 data.m_Backends,
3665 isSupported,
3666 input0.GetTensorInfo(),
3667 input1.GetTensorInfo(),
3668 outputInfo);
3669 };
3670
3671 if(IsDynamicTensor(outputInfo))
3672 {
3673 isSupported = AreDynamicTensorsSupported();
3674 }
3675 else
3676 {
3677 validateFunc(outputInfo, isSupported);
3678 }
3679
Mike Kelly0a879362019-07-29 16:56:31 +01003680 if (!isSupported)
3681 {
3682 return false;
3683 }
3684
3685 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
3686 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3687
3688 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3689 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3690
3691 if (endLayer)
3692 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003693 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003694 if (!isReshapeSupported)
3695 {
3696 return false;
3697 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003698 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly0a879362019-07-29 16:56:31 +01003699 }
3700
3701 return Fail("%s: ProcessActivation failed", __func__);
3702}
3703
Finn Williams23b87b32019-07-30 11:44:05 +01003704template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003705 typename HalOperation = typename HalPolicy::Operation,
3706 typename HalModel = typename HalPolicy::Model>
3707bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003708{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003709 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003710
3711 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3712 if (!input.IsValid())
3713 {
3714 return Fail("%s: Operation has invalid inputs", __func__);
3715 }
3716
3717 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3718 unsigned int rank = inputInfo.GetNumDimensions();
3719 if (rank > 4)
3720 {
3721 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3722 }
3723
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003724 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003725 if (!output)
3726 {
3727 return Fail("%s: Could not read output 0", __func__);
3728 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003729
3730 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003731 {
3732 return Fail("%s: Dynamic output tensors are not supported", __func__);
3733 }
3734
3735 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3736 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003737 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003738
3739 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3740
3741 std::vector<int32_t> axis;
3742 if (!axisOperand)
3743 {
3744 axis.assign(dimensionSequence,
3745 dimensionSequence + rank);
3746 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003747 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003748 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003749 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003750 }
3751
3752 std::vector<uint32_t> outputDims;
3753 for (unsigned int i = 0; i < rank; i++)
3754 {
3755 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3756 auto currentDimension = inputInfo.GetShape()[i];
3757 if (skipSqueeze || currentDimension != 1)
3758 {
3759 outputDims.push_back(currentDimension);
3760 }
3761 }
3762
3763 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3764
3765 armnn::TensorInfo outputInfo = inputInfo;
3766 outputInfo.SetShape(outShape);
3767
3768 armnn::ReshapeDescriptor reshapeDesc;
3769 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3770
3771 bool isSupported = false;
3772 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3773 IsReshapeSupported,
3774 data.m_Backends,
3775 isSupported,
3776 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003777 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003778 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003779
Mike Kelly46272802019-08-14 17:00:48 +01003780 if (!isSupported)
3781 {
3782 return false;
3783 }
3784
3785 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3786 assert(layer != nullptr);
3787 input.Connect(layer->GetInputSlot(0));
3788
3789 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3790}
3791
3792template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003793 typename HalOperation = typename HalPolicy::Operation,
3794 typename HalModel = typename HalPolicy::Model>
3795bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003796{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003797 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003798
3799 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3800 if (!input.IsValid())
3801 {
3802 return Fail("%s: Operation has invalid inputs", __func__);
3803 }
3804
3805 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3806 unsigned int rank = inputInfo.GetNumDimensions();
3807 if (rank > 4)
3808 {
3809 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3810 }
3811
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003812 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003813 if (!output)
3814 {
3815 return Fail("%s: Could not read output 0", __func__);
3816 }
3817
3818 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003819
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003820 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3821 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3822 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003823
3824 std::vector<int32_t> beginValues;
3825 std::vector<int32_t> endValues;
3826 std::vector<int32_t> stridesValues;
3827
3828 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003829 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003830 {
3831 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3832 {
3833 return false;
3834 }
3835
3836 if (operandValues.size() != rank)
3837 {
3838 return false;
3839 }
3840
3841 return true;
3842 };
3843
3844 if (!ValidateInputOperands(*beginOperand, beginValues)
3845 || !ValidateInputOperands(*endOperand, endValues)
3846 || !ValidateInputOperands(*stridesOperand, stridesValues))
3847 {
3848 return Fail("%s: Operation has invalid input operand", __func__);
3849 }
3850
3851 // Stride cannot have value '0'
3852 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3853 {
3854 return Fail("%s: Stride must be non-zero value.", __func__);
3855 }
3856
3857 armnn::StridedSliceDescriptor descriptor;
3858 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3859 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3860 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3861 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3862
3863 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3864 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3865 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3866 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3867 {
3868 return Fail("%s: Operation has invalid inputs", __func__);
3869 }
3870
3871 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003872 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3873 {
3874 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3875 IsStridedSliceSupported,
3876 data.m_Backends,
3877 isSupported,
3878 inputInfo,
3879 outputInfo,
3880 descriptor);
3881 };
3882
3883 if(IsDynamicTensor(outputInfo))
3884 {
3885 isSupported = AreDynamicTensorsSupported();
3886 }
3887 else
3888 {
3889 validateFunc(outputInfo, isSupported);
3890 }
3891
Mike Kelly46272802019-08-14 17:00:48 +01003892 if (!isSupported)
3893 {
3894 return false;
3895 }
3896
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003897 // Check if slice can fit in a inferred output
3898 armnn::TensorShape inputShape = inputInfo.GetShape();
3899 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3900 {
3901 int stride = descriptor.m_Stride[i];
3902 int start = descriptor.GetStartForAxis(inputShape, i);
3903 int stop = descriptor.GetStopForAxis(inputShape, i, start);
3904
3905 if (descriptor.m_ShrinkAxisMask & (1 << i))
3906 {
3907 // If the difference between the start point and the end point of the slice on an axis being shrunk
3908 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3909 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3910 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3911 {
3912 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3913 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003914
3915 if(stride < 0)
3916 {
3917 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3918 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003919 }
3920 }
3921
Mike Kelly46272802019-08-14 17:00:48 +01003922 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3923 assert(layer != nullptr);
3924 input.Connect(layer->GetInputSlot(0));
3925
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003926 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003927}
3928
3929template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003930 typename HalOperation = typename HalPolicy::Operation,
3931 typename HalModel = typename HalPolicy::Model>
3932bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003933{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003934 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003935 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003936
3937 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3938 if (!input.IsValid())
3939 {
3940 return Fail("%s: Operation has invalid inputs", __func__);
3941 }
3942
3943 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3944 unsigned int rank = inputInfo.GetNumDimensions();
3945 if (rank > 4)
3946 {
3947 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3948 }
3949
3950 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3951 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003952 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003953
3954 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003955 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003956 {
Mike Kelly46272802019-08-14 17:00:48 +01003957 for (unsigned int i = rank; i > 0; i--)
3958 {
3959 perm[rank - i] = boost::numeric_cast<int> (i - 1);
3960 }
3961 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003962 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003963 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003964 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003965 }
3966
3967 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3968
Mike Kelly4a956582020-02-28 10:32:09 +00003969 armnn::TransposeDescriptor transposeDesc;
3970 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003971
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003972 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003973 if (!output)
3974 {
3975 return Fail("%s: Could not read output 0", __func__);
3976 }
3977
3978 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3979
3980 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003981 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3982 {
3983 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3984 IsTransposeSupported,
3985 data.m_Backends,
3986 isSupported,
3987 inputInfo,
3988 outputInfo,
3989 transposeDesc);
3990 };
3991
3992 if(IsDynamicTensor(outputInfo))
3993 {
3994 isSupported = AreDynamicTensorsSupported();
3995 }
3996 else
3997 {
3998 validateFunc(outputInfo, isSupported);
3999 }
4000
Mike Kelly46272802019-08-14 17:00:48 +01004001 if (!isSupported)
4002 {
4003 return false;
4004 }
4005
Mike Kelly4a956582020-02-28 10:32:09 +00004006 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01004007 assert(layer != nullptr);
4008 input.Connect(layer->GetInputSlot(0));
4009
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004010 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01004011}
4012
4013template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01004014 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01004015 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01004016 typename HalModel = typename HalPolicy::Model>
4017bool ConvertBatchToSpaceNd(const HalOperation& operation,
4018 const HalModel& model,
4019 ConversionData& data)
4020{
Finn Williams23b87b32019-07-30 11:44:05 +01004021
4022 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4023 if (!input.IsValid())
4024 {
4025 return Fail("%s: Operation has invalid inputs", __func__);
4026 }
4027
4028 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4029 if (!output)
4030 {
4031 return Fail("%s: Could not read output 0", __func__);
4032 }
4033
4034 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004035
4036 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4037 if (!blockOperand)
4038 {
4039 return Fail("%s: Could not read input 1", __func__);
4040 }
4041
4042 // Convert the block operand to int32
4043 std::vector<int32_t> block;
4044 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4045 {
4046 return Fail("%s: Input 1 has invalid values", __func__);
4047 }
4048
4049 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4050
4051 unsigned int rank = inputInfo.GetNumDimensions();
4052 if (rank != 4)
4053 {
4054 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4055 }
4056
4057 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4058 {
4059 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4060 " greater than or equal to 1", __func__);
4061 }
4062
4063 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4064 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4065 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4066
Kevin May42477c12020-03-26 13:34:14 +00004067 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004068 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004069 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004070 }
4071 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4072 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4073
4074 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004075 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4076 {
4077 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4078 IsBatchToSpaceNdSupported,
4079 data.m_Backends,
4080 isSupported,
4081 inputInfo,
4082 outputInfo,
4083 batchToSpaceNdDesc);
4084 };
4085
4086 if(!IsDynamicTensor(outputInfo))
4087 {
4088 validateFunc(outputInfo, isSupported);
4089 }
4090 else
4091 {
4092 isSupported = AreDynamicTensorsSupported();
4093 }
4094
4095
Finn Williams23b87b32019-07-30 11:44:05 +01004096 if (!isSupported)
4097 {
4098 return false;
4099 }
4100
4101 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4102 assert(layer != nullptr);
4103 input.Connect(layer->GetInputSlot(0));
4104
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004105 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004106}
Mike Kelly0a879362019-07-29 16:56:31 +01004107
Finn Williamsd74c5052019-07-30 17:06:00 +01004108template<typename HalPolicy,
4109 typename HalOperation = typename HalPolicy::Operation,
4110 typename HalOperand = typename HalPolicy::Operand,
4111 typename HalModel = typename HalPolicy::Model>
4112bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4113{
4114 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4115 if (!input.IsValid())
4116 {
4117 return Fail("%s: Operation has invalid inputs", __func__);
4118 }
4119
4120 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4121 unsigned int rank = inputInfo.GetNumDimensions();
4122 unsigned int spatialDim = rank - 2;
4123
4124 if (rank != 4)
4125 {
4126 Fail("%s: Only inputs with rank 4 are supported", __func__);
4127 }
4128
4129 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4130 if (!output)
4131 {
4132 return Fail("%s: Could not read output 0", __func__);
4133 }
4134
4135 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004136
4137 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4138 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4139
4140 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4141 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4142 {
4143 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4144 }
4145
4146 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004147 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4148 {
4149 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4150 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004151 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4152 {
4153 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4154 }
4155
4156 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4157 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4158 {
4159 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4160 }
4161
4162 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4163 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004164 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4165 {
4166 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4167 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004168 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4169 {
4170 int paddingBeforeInput = paddings[i];
4171 int paddingAfterInput = paddings[i + 1];
4172 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4173 {
4174 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4175 }
4176
4177 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4178 }
4179
4180 armnn::SpaceToBatchNdDescriptor descriptor;
4181 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4182 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4183 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4184
Kevin May42477c12020-03-26 13:34:14 +00004185 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004186 {
4187 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4188 }
4189
4190 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004191 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4192 {
4193 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4194 IsSpaceToBatchNdSupported,
4195 data.m_Backends,
4196 isSupported,
4197 inputInfo,
4198 outputInfo,
4199 descriptor);
4200 };
4201
4202 if(IsDynamicTensor(outputInfo))
4203 {
4204 isSupported = AreDynamicTensorsSupported();
4205 }
4206 else
4207 {
4208 validateFunc(outputInfo, isSupported);
4209 }
4210
Finn Williamsd74c5052019-07-30 17:06:00 +01004211 if (!isSupported)
4212 {
4213 return false;
4214 }
4215
4216 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4217 assert(layer != nullptr);
4218 input.Connect(layer->GetInputSlot(0));
4219
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004220 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004221}
4222
saoste01b8471482018-10-10 09:44:51 +01004223} // namespace armnn_driver