blob: 1d182fadd7ead89333333194c98d202647fa0b35 [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/BackendHelper.hpp>
Jan Eilers0b7a4192020-03-09 18:20:42 +000012#include <armnn/utility/IgnoreUnused.hpp>
Matthew Sloyan9b088d92020-09-14 15:12:55 +010013#include <armnn/utility/NumericCast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010014
Matteo Martincigh00d6ed12019-11-28 17:13:24 +000015#include <armnnUtils/DataLayoutIndexed.hpp>
Mike Kelly4a956582020-02-28 10:32:09 +000016#include <armnnUtils/Transpose.hpp>
arovir01b0717b52018-09-05 17:03:25 +010017
Mike Kelly46272802019-08-14 17:00:48 +010018#include "1.0/FullyConnected.hpp"
19
arovir01b0717b52018-09-05 17:03:25 +010020#include <ActivationFunctor.h>
21#include <CpuExecutor.h>
22#include <OperationsUtils.h>
23
James Ward4e22f602020-10-20 15:50:33 +010024#include <armnnUtils/FloatingPointComparison.hpp>
arovir01b0717b52018-09-05 17:03:25 +010025
26#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010027#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010028
29namespace armnn_driver
30{
31
32///
33/// Helper classes
34///
35
Kevin Mayec1e5b82020-02-26 17:00:39 +000036#ifdef ARMNN_ANDROID_R
37using OperandType = android::nn::hal::OperandType;
38#endif
39
Sadik Armagan188675f2021-02-12 17:16:42 +000040#ifdef ARMNN_ANDROID_S
41#include <nnapi/Types.h>
42#endif
43
44
arovir01b0717b52018-09-05 17:03:25 +010045struct ConversionData
46{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010047 ConversionData(const std::vector<armnn::BackendId>& backends)
48 : m_Backends(backends)
49 , m_Network(nullptr, nullptr)
Finn Williams291a16b2020-08-19 22:54:00 +010050 , m_DynamicInputsEncountered(false)
arovir01b0717b52018-09-05 17:03:25 +010051 {}
52
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010053 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010054 armnn::INetworkPtr m_Network;
55 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
56 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
Finn Williams291a16b2020-08-19 22:54:00 +010057 bool m_DynamicInputsEncountered;
arovir01b0717b52018-09-05 17:03:25 +010058};
59
60class LayerInputHandle
61{
62public:
63 LayerInputHandle();
64 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
65
66 bool IsValid() const;
67
68 void Connect(armnn::IInputSlot& inputSlot);
69
Finn Williamsa4983ce2020-07-23 12:55:12 +010070 void Disconnect(armnn::IInputSlot& inputSlot);
71
arovir01b0717b52018-09-05 17:03:25 +010072 const armnn::TensorInfo& GetTensorInfo() const;
73
74private:
75 armnn::IOutputSlot* m_OutputSlot;
76 bool m_Valid;
77 armnn::TensorInfo m_TensorInfo;
78};
79
80class ConstTensorPin
81{
82public:
83 // Creates an invalid tensor pin (can be used to signal errors)
84 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
85 ConstTensorPin(bool optional = false);
86
87 // @param tensorInfo TensorInfo associated with the tensor.
88 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
89 // the model being converted.
90 // @param numBytes Number of bytes for the tensor data.
Jan Eilersa71c0632021-04-12 13:12:19 +010091 ConstTensorPin(armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
arovir01b0717b52018-09-05 17:03:25 +010092 const armnn::PermutationVector& mappings);
93
94 ConstTensorPin(const ConstTensorPin& other) = delete;
95 ConstTensorPin(ConstTensorPin&& other) = default;
96
97 bool IsValid() const;
98 bool IsOptional() const;
99
100 const armnn::ConstTensor& GetConstTensor() const;
101 const armnn::ConstTensor* GetConstTensorPtr() const;
102
103private:
104 armnn::ConstTensor m_ConstTensor;
105
106 // Owned memory for swizzled tensor data, only required if the tensor needed
107 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
108 // the pools associated with the model being converted.
109 std::vector<uint8_t> m_SwizzledTensorData;
110
111 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
112 bool m_Optional;
113};
114
115} // namespace armnn_driver
116
117///
118/// Utility functions
119///
120
121namespace
122{
123
124using namespace armnn_driver;
125using namespace android::nn;
126
127// Convenience function to log the reason for failing to convert a model.
128// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
129template<class... Args>
130static bool Fail(const char* formatStr, Args&&... args)
131{
132 ALOGD(formatStr, std::forward<Args>(args)...);
133 return false;
134}
135
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100136// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
137// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
138#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100139try \
140{ \
141 for (auto&& backendId : backends) \
142 { \
143 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
Francis Murtagh01824732021-01-28 14:26:27 +0000144 if (layerSupportObject.IsBackendRegistered()) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100145 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100146 std::string reasonIfUnsupported; \
147 supported = \
Francis Murtagh01824732021-01-28 14:26:27 +0000148 layerSupportObject.func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100149 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100150 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100151 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100152 } \
153 else \
154 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100155 if (reasonIfUnsupported.size() > 0) \
156 { \
157 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
158 } \
159 else \
160 { \
161 ALOGD("%s: not supported by armnn", funcName); \
162 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100163 } \
164 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100165 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100166 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100167 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100168 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100169 } \
170 if (!supported) \
171 { \
172 ALOGD("%s: not supported by any specified backend", funcName); \
173 } \
174} \
175catch (const armnn::InvalidArgumentException &e) \
176{ \
177 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
178}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100179
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000180template<typename HalOperand>
181armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100182{
183 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
184}
185
Matthew Bentham912b3622019-05-03 15:49:14 +0100186inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100187{
Matthew Bentham912b3622019-05-03 15:49:14 +0100188 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
189 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
190 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100191}
192
Kevin May42477c12020-03-26 13:34:14 +0000193#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100194
Keith Davis71006492020-01-06 17:44:16 +0000195// Support within the 1.2 driver for specific tensor data types
Mike Kellyb5fdf382019-06-11 16:35:25 +0100196inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
197{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000198 return type == V1_2::OperandType::BOOL ||
Sadik Armagan793a70c2020-03-19 13:54:04 +0000199 type == V1_2::OperandType::TENSOR_BOOL8 ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000200 type == V1_2::OperandType::TENSOR_FLOAT16 ||
201 type == V1_2::OperandType::TENSOR_FLOAT32 ||
202 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
Keith Davis71006492020-01-06 17:44:16 +0000203 type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000204 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
205 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100206 type == V1_2::OperandType::TENSOR_INT32;
207}
208
209#endif
210
Kevin May42477c12020-03-26 13:34:14 +0000211#ifdef ARMNN_ANDROID_NN_V1_3
212
213// Support within the 1.3 driver for specific tensor data types
214inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
215{
216 return type == V1_3::OperandType::BOOL ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100217 type == V1_3::OperandType::TENSOR_BOOL8 ||
Kevin May42477c12020-03-26 13:34:14 +0000218 type == V1_3::OperandType::TENSOR_FLOAT16 ||
219 type == V1_3::OperandType::TENSOR_FLOAT32 ||
220 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100221 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
Kevin May42477c12020-03-26 13:34:14 +0000222 type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
223 type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
224 type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
225 type == V1_3::OperandType::TENSOR_INT32;
226}
227
228#endif
229
Mike Kellyb5fdf382019-06-11 16:35:25 +0100230inline bool IsBool(V1_0::Operand)
231{
232 return false;
233}
234
Kevin May42477c12020-03-26 13:34:14 +0000235inline bool Is12OrLaterOperand(V1_0::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100236{
237 return false;
238}
239
Kevin May42477c12020-03-26 13:34:14 +0000240#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100241
242inline bool IsBool(V1_2::Operand operand)
243{
244 return operand.type == V1_2::OperandType::BOOL;
245}
246
Sadik Armagan61113162019-07-25 09:09:40 +0100247/// Checks if a operand is 1_2 Operand
Kevin May42477c12020-03-26 13:34:14 +0000248inline bool Is12OrLaterOperand(V1_2::Operand)
249{
250 return true;
251}
252
253#endif
254
255#ifdef ARMNN_ANDROID_NN_V1_3
256
257inline bool IsBool(V1_3::Operand operand)
258{
259 return operand.type == V1_3::OperandType::BOOL;
260}
261
262/// Checks if a operand is 1_2 Operand
263inline bool Is12OrLaterOperand(V1_3::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100264{
265 return true;
266}
267
Mike Kellyb5fdf382019-06-11 16:35:25 +0100268#endif
269
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100270template<typename LayerHandleType>
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000271armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
272 LayerHandleType& inputLayer,
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100273 armnn::TensorInfo reshapeInfo)
274{
275 armnn::ReshapeDescriptor reshapeDescriptor;
276 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
277
278 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +0100279 if (!reshapeLayer)
280 {
281 throw armnn::RuntimeException("ReshapeLayer is null");
282 }
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100283
284 // Attach the input layer to the reshape layer
285 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
286 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
287
288 return *reshapeLayer;
289}
290
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000291bool BroadcastTensor(LayerInputHandle& input0,
292 LayerInputHandle& input1,
293 armnn::IConnectableLayer* startLayer,
294 ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100295{
Mike Kellye2d611e2021-10-14 12:35:58 +0100296 if (!startLayer)
297 {
298 throw armnn::RuntimeException("StartLayer is null");
299 }
arovir01b0717b52018-09-05 17:03:25 +0100300
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100301 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
302 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
303
304 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
305 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
306
307 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100308 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100309 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
310 input0.Connect(startLayer->GetInputSlot(0));
311 input1.Connect(startLayer->GetInputSlot(1));
312
Sadik Armagan64b19b52019-08-19 09:49:58 +0100313 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100314 }
315
316 // Since the number of dimensions do not match then we need to add degenerate dimensions
317 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
318
319 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100320 unsigned int sizeDifference = std::abs(armnn::numeric_cast<int>(inputDimensions0) -
321 armnn::numeric_cast<int>(inputDimensions1));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100322
323 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
324 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
325 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
326
327 const armnn::TensorShape& smallShape = smallInfo.GetShape();
328 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
329 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
330 {
331 reshapedDimensions[i] = smallShape[i - sizeDifference];
332 }
333
334 armnn::TensorInfo reshapedInfo = smallInfo;
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100335 reshapedInfo.SetShape(armnn::TensorShape{ armnn::numeric_cast<unsigned int>(reshapedDimensions.size()),
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100336 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100337
338 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
339 armnn::ReshapeDescriptor reshapeDescriptor;
340
341 bool isSupported = false;
342 FORWARD_LAYER_SUPPORT_FUNC(__func__,
343 IsReshapeSupported,
344 data.m_Backends,
345 isSupported,
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +0000346 smallInfo,
Sadik Armagan64b19b52019-08-19 09:49:58 +0100347 reshapedInfo,
348 reshapeDescriptor);
349 if (!isSupported)
350 {
351 return false;
352 }
353
Mike Kellye2d611e2021-10-14 12:35:58 +0100354 if (!data.m_Network)
355 {
356 throw armnn::RuntimeException("Network is null");
357 }
358
Sadik Armagan64b19b52019-08-19 09:49:58 +0100359 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100360
361 if (input0IsSmaller)
362 {
363 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
364 //
365 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100366 // | |
367 // Reshape |
368 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100369 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100370
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100371 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
372 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100373 }
374 else
375 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100376 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
377 //
378 // Input0 Input1
379 // | |
380 // | Reshape
381 // \ /
382 // StartLayer
383
arovir01b0717b52018-09-05 17:03:25 +0100384 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100385 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100386 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100387
388 return true;
arovir01b0717b52018-09-05 17:03:25 +0100389}
390
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000391void CalcPadding(uint32_t input,
392 uint32_t kernel,
393 uint32_t stride,
394 uint32_t& outPadHead,
395 uint32_t& outPadTail,
arovir01b0717b52018-09-05 17:03:25 +0100396 android::nn::PaddingScheme scheme)
397{
398 int32_t padHead;
399 int32_t padTail;
400 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100401 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
402 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
arovir01b0717b52018-09-05 17:03:25 +0100403}
404
Kevin May42477c12020-03-26 13:34:14 +0000405#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly86b36d42019-07-12 16:39:33 +0100406
407void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
408 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
409{
410 int32_t padHead;
411 int32_t padTail;
412 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
Matthew Sloyan9b088d92020-09-14 15:12:55 +0100413 outPadHead = armnn::numeric_cast<uint32_t>(padHead);
414 outPadTail = armnn::numeric_cast<uint32_t>(padTail);
Mike Kelly86b36d42019-07-12 16:39:33 +0100415}
416
Mike Kelly26123db2020-01-15 10:02:33 +0000417void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100418 int32_t& outPadTail, android::nn::PaddingScheme scheme)
419{
420 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
421}
422
Mike Kelly86b36d42019-07-12 16:39:33 +0100423#endif
424
Matthew Bentham912b3622019-05-03 15:49:14 +0100425Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100426{
427 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100428 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100429 shape.dimensions = operand.dimensions;
430 shape.scale = operand.scale;
431 shape.offset = operand.zeroPoint;
432 return shape;
433}
434
Kevin May42477c12020-03-26 13:34:14 +0000435#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly46272802019-08-14 17:00:48 +0100436
437Shape GetOperandShape(const V1_2::Operand& operand)
438{
439 Shape shape;
440 shape.type = OperandType(operand.type);
441 shape.dimensions = operand.dimensions;
442 shape.scale = operand.scale;
443 shape.offset = operand.zeroPoint;
444 return shape;
445}
446
447#endif
448
Kevin May42477c12020-03-26 13:34:14 +0000449#ifdef ARMNN_ANDROID_NN_V1_3
450
451Shape GetOperandShape(const V1_3::Operand& operand)
452{
453 Shape shape;
454 shape.type = OperandType(operand.type);
455 shape.dimensions = operand.dimensions;
456 shape.scale = operand.scale;
457 shape.offset = operand.zeroPoint;
458 return shape;
459}
460
461#endif
462
arovir01b0717b52018-09-05 17:03:25 +0100463// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
464// 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 +0100465// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
466// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100467void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000468 const armnn::TensorInfo& weightInfo,
469 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100470{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000471 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100472 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000473 // NOTE: Bias scale is always set to 0 for per-axis quantization and
474 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
475 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100476 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000477 return biasScale * inputInfo.GetQuantizationScale();
478 };
479
480 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
481 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
482
483 biasInfo.SetQuantizationScales(biasScales);
Jan Eilersa20d2b82021-04-27 09:21:08 +0100484 // bias is expected to be a 1d tensor, set qdim=0
485 biasInfo.SetQuantizationDim(0);
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000486
487 ALOGV("Bias quantization params have been updated for per-axis quantization");
488 }
489 else
490 {
491 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
492 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
493 {
James Ward4e22f602020-10-20 15:50:33 +0100494 if (armnnUtils::within_percentage_tolerance(biasInfo.GetQuantizationScale(), expectedBiasScale, 1.0f))
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000495 {
496 ALOGW("Bias quantization scale has been modified to match input * weights");
497 biasInfo.SetQuantizationScale(expectedBiasScale);
498 }
arovir01b0717b52018-09-05 17:03:25 +0100499 }
500 }
501}
502
503// 4D Tensor Permutations
504const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
David Monahan7f492ac2020-10-16 10:36:29 +0100505const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
arovir01b0717b52018-09-05 17:03:25 +0100506const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
507
508// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000509const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
510const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100511
512template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000513armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
514 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100515{
516 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000517 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
Mike Kellye2d611e2021-10-14 12:35:58 +0100518 if (!layer)
519 {
520 throw armnn::RuntimeException("TransposeLayer is null");
521 }
arovir01b0717b52018-09-05 17:03:25 +0100522 // Connect input to swizzle layer
523 input.Connect(layer->GetInputSlot(0));
524
525 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000526 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100527 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
528
529 return *layer;
530}
531
arovir01b0717b52018-09-05 17:03:25 +0100532bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
533 const armnn::TensorShape & outputShape,
534 uint32_t concatDim)
535{
536 // Validate the output shape is correct given the input shapes (which have just been validated)
537 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
538 if (outputShape.GetNumDimensions() != numDimensions)
539 {
540 return Fail("%s: Output shape has wrong number of dimensions", __func__);
541 }
542
543 unsigned int outputSizeAlongConcatenatedDimension = 0;
544 for (unsigned int i = 0; i < inputShapes.size(); i++)
545 {
546 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
547 }
548
549 for (unsigned int i = 0; i < numDimensions; ++i)
550 {
551 if (i == concatDim)
552 {
553 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
554 {
555 return Fail(
556 "%s: Invalid output shape for dimension %d (%d != %d)",
557 __func__,
558 i,
559 outputShape[i],
560 outputSizeAlongConcatenatedDimension);
561 }
562 }
563 else
564 {
565 if (outputShape[i] != inputShapes[0][i])
566 {
567 return Fail("%s: Invalid output shape", __func__);
568 }
569 }
570 }
571
572 return true;
573}
574
575bool RequiresReshape(armnn::TensorShape & inputShape)
576{
577 return inputShape.GetNumDimensions() < 3;
578}
579
arovir01b0717b52018-09-05 17:03:25 +0100580void SwizzleInputs(armnn::INetwork& network,
581 std::vector<LayerInputHandle>& inputs,
582 std::vector<armnn::TensorShape>& inputShapes,
583 const armnn::PermutationVector& mapping)
584{
585 if (!mapping.IsEqual(IdentityPermutation4D))
586 {
587 size_t nInputs = inputs.size();
588 for (size_t i=0; i<nInputs; ++i)
589 {
590 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000591 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100592 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
593 auto& outputInfo = outputSlot.GetTensorInfo();
594 // replace inputs with the swizzled ones
595 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
596 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
597 }
598 }
599}
600
Teresa Charlin185f5882020-04-06 21:59:18 +0100601bool TransposeInputTensors(ConversionData& data,
602 std::vector<LayerInputHandle>& inputs,
603 std::vector<armnn::TensorShape>& inputShapes,
604 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000605{
David Monahan7f492ac2020-10-16 10:36:29 +0100606 // If we have a IdentityPermutation4D or IdentityPermutation3D then we are not permuting
607 if (!mapping.IsEqual(IdentityPermutation4D) && !mapping.IsEqual(IdentityPermutation3D))
Kevin Mayaed08ac2019-12-12 16:33:31 +0000608 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100609 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000610 size_t nInputs = inputs.size();
611 for (size_t i=0; i<nInputs; ++i)
612 {
613 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000614 armnn::TransposeDescriptor transposeDesc;
615 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100616 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000617
618 bool isSupported = false;
619 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000620 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000621 data.m_Backends,
622 isSupported,
623 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100624 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000625 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000626 if (!isSupported)
627 {
628 return false;
629 }
630
631 }
632 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
633 }
634 return true;
635}
636
637
narpra01f176d5a2018-11-18 20:17:48 +0000638bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
639 int32_t & concatDimension,
640 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100641{
narpra01f176d5a2018-11-18 20:17:48 +0000642 bool needPermute = false;
Mike Kellye2d611e2021-10-14 12:35:58 +0100643
644 if (numberOfDimensions < 3)
645 {
646 return Fail("%s: Invalid numberOfDimensions: %i < 3", __func__, numberOfDimensions);
647 }
arovir01b0717b52018-09-05 17:03:25 +0100648
649 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000650 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
651 // or along dimension 0 or 2 for a 3-D tensor.
652 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100653 {
narpra01f176d5a2018-11-18 20:17:48 +0000654 concatDimension = 1;
655 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
656 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100657 }
narpra01f176d5a2018-11-18 20:17:48 +0000658 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100659 {
narpra01f176d5a2018-11-18 20:17:48 +0000660 concatDimension = 0;
661 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
662 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100663 }
David Monahan7f492ac2020-10-16 10:36:29 +0100664 // If the tensor is 3-D and the concat dimension is 2 then we don't need to permute but we do need to change the
665 // permutation identity to only have 3 dimensions
666 else if (numberOfDimensions == 3 && concatDimension == 2)
667 {
668 permutationPair = std::make_pair(IdentityPermutation3D, IdentityPermutation3D);
669 }
narpra01f176d5a2018-11-18 20:17:48 +0000670 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100671}
672
673} // anonymous namespace
674
675namespace armnn_driver
676{
677
678//// Creates an ArmNN activation layer and connects it to the given layer, if the
679//// passed in AndroidNN activation function requires so.
680//// @return The end layer of the sequence of layers built for the given AndroidNN
681//// activation function or nullptr if an error occurred (e.g. unsupported activation).
682//// Note that the end layer matches the input layer if no activation is required
683//// (the sequence of layers has length 1).
684armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
685 ActivationFn activation,
686 armnn::IConnectableLayer* prevLayer,
687 ConversionData& data);
688
689} // namespace armnn_driver
690
691///
692/// Utility templates
693///
694
695namespace armnn_driver
696{
697
698using namespace android::nn;
699
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100700template<typename HalPolicy,
701 typename HalOperand = typename HalPolicy::Operand,
702 typename HalOperation = typename HalPolicy::Operation,
703 typename HalModel = typename HalPolicy::Model>
704const HalOperand* GetInputOperand(const HalOperation& operation,
705 uint32_t inputIndex,
706 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100707 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100708{
709 if (inputIndex >= operation.inputs.size())
710 {
saoste01b8471482018-10-10 09:44:51 +0100711 if (failOnIndexOutOfBounds)
712 {
Mike Kellye2d611e2021-10-14 12:35:58 +0100713 Fail("%s: Invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
saoste01b8471482018-10-10 09:44:51 +0100714 }
arovir01b0717b52018-09-05 17:03:25 +0100715 return nullptr;
716 }
717
Kevin May42477c12020-03-26 13:34:14 +0000718 // Model should have been validated beforehand
Mike Kellye2d611e2021-10-14 12:35:58 +0100719 if (operation.inputs[inputIndex] >= getMainModel(model).operands.size())
720 {
721 Fail("%s: invalid model index: %i >= %i", __func__, inputIndex, getMainModel(model).operands.size());
722 return nullptr;
723 }
724
Kevin May42477c12020-03-26 13:34:14 +0000725 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100726}
727
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100728template<typename HalPolicy,
729 typename HalOperand = typename HalPolicy::Operand,
730 typename HalOperation = typename HalPolicy::Operation,
731 typename HalModel = typename HalPolicy::Model>
732const HalOperand* GetOutputOperand(const HalOperation& operation,
733 uint32_t outputIndex,
734 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100735{
736 if (outputIndex >= operation.outputs.size())
737 {
738 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
739 return nullptr;
740 }
741
742 // Model should have been validated beforehand
Mike Kellye2d611e2021-10-14 12:35:58 +0100743 if (operation.inputs[outputIndex] >= getMainModel(model).operands.size())
744 {
745 Fail("%s: invalid model index: %i >= %i", __func__, outputIndex, getMainModel(model).operands.size());
746 return nullptr;
747 }
Kevin May42477c12020-03-26 13:34:14 +0000748 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100749}
750
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100751template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100752 typename HalOperand = typename HalPolicy::Operand,
753 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100754const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100755 const HalModel& model,
756 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000757 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100758{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100759 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100760
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100761 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100762 switch (operand.lifetime)
763 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100764 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100765 {
766 // Constant found in model.operandValues
767 valueStart = &model.operandValues[operand.location.offset];
768 break;
769 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100770 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100771 {
772 // Constant specified via a Memory object
773 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
774 break;
775 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100776 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000777 {
778 // An optional input tensor with no values is not an error so should not register as a fail
779 if (optional)
780 {
781 valueStart = nullptr;
782 break;
783 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100784 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000785 }
arovir01b0717b52018-09-05 17:03:25 +0100786 default:
787 {
788 // Unsupported/invalid (e.g. can't get value of an input to the model)
789 Fail("%s: unsupported/invalid operand lifetime: %s",
790 __func__, toString(operand.lifetime).c_str());
791 valueStart = nullptr;
792 }
793 }
794
795 return valueStart;
796}
797
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100798template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100799 typename HalOperation = typename HalPolicy::Operation,
800 typename HalModel = typename HalPolicy::Model,
801 typename HalOperandType = typename HalPolicy::OperandType>
802bool GetOperandType(const HalOperation& operation,
803 uint32_t inputIndex,
804 const HalModel& model,
805 HalOperandType& type)
806{
807 using HalOperand = typename HalPolicy::Operand;
808
809 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
810 if (!operand)
811 {
812 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
813 }
814
815 type = operand->type;
816 return true;
817}
818
819template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000820 typename HalOperand = typename HalPolicy::Operand>
821bool IsOperandConstant(const HalOperand& operand)
822{
823 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
824
825 HalOperandLifeTime lifetime = operand.lifetime;
826
827 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
828 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
829 lifetime == HalOperandLifeTime::NO_VALUE;
830}
831
832template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100833 typename HalOperand = typename HalPolicy::Operand,
834 typename HalModel = typename HalPolicy::Model>
835ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
836 const HalModel& model,
837 const ConversionData& data,
838 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
839 const armnn::TensorShape* overrideTensorShape = nullptr,
840 bool optional = false)
841{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100842 if (!IsOperandTypeSupportedForTensors(operand.type))
843 {
844 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
845 return ConstTensorPin();
846 }
847
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000848 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100849 {
850 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
851 return ConstTensorPin();
852 }
853
854 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
855 if (!valueStart)
856 {
857 if (optional)
858 {
859 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
860 return ConstTensorPin(true);
861 }
862 // mandatory tensor with no values
863 Fail("%s: failed to get operand address", __func__);
864 return ConstTensorPin();
865 }
866
867 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000868
Matthew Sloyan29cc9612021-07-16 10:21:12 +0100869 // Make sure isConstant flag is set.
870 tensorInfo.SetConstant();
871
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100872 if (overrideTensorShape != nullptr)
873 {
874 tensorInfo.SetShape(*overrideTensorShape);
875 }
876 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
877}
878
879template<typename HalPolicy,
880 typename HalOperation = typename HalPolicy::Operation,
881 typename HalModel = typename HalPolicy::Model>
882ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
883 uint32_t inputIndex,
884 const HalModel& model,
885 const ConversionData& data,
886 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
887 const armnn::TensorShape* overrideTensorShape = nullptr,
888 bool optional = false)
889{
890 using HalOperand = typename HalPolicy::Operand;
891
892 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
893 if (!operand)
894 {
895 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
896 return ConstTensorPin();
897 }
898 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
899 model,
900 data,
901 dimensionMappings,
902 overrideTensorShape,
903 optional);
904}
905
906template<typename HalPolicy,
907 typename OutputType,
908 typename HalOperandType = typename HalPolicy::OperandType,
909 typename HalOperation = typename HalPolicy::Operation,
910 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100911bool GetInputScalar(const HalOperation& operation,
912 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100913 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100914 OutputType& outValue,
915 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100916 const ConversionData& data,
917 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100918{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100919 using HalOperand = typename HalPolicy::Operand;
920
921 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100922 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100923 {
924 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
925 }
926
Sadik Armagan813f2302020-05-19 14:10:30 +0100927 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100928 {
929 return Fail("%s: unexpected operand type: %s (should be %s)",
930 __func__, toString(operand->type).c_str(), toString(type).c_str());
931 }
932
Sadik Armagan813f2302020-05-19 14:10:30 +0100933 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100934 {
935 return Fail("%s: incorrect operand location length: %i (should be %i)",
936 __func__, operand->location.length, sizeof(OutputType));
937 }
938
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100939 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100940 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100941 {
942 return Fail("%s: failed to get address for operand", __func__);
943 }
944
Sadik Armagan813f2302020-05-19 14:10:30 +0100945 if(!optional)
946 {
947 outValue = *(static_cast<const OutputType*>(valueAddress));
948 }
949
arovir01b0717b52018-09-05 17:03:25 +0100950 return true;
951}
952
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100953template<typename HalPolicy,
954 typename HalOperation = typename HalPolicy::Operation,
955 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100956bool GetInputInt32(const HalOperation& operation,
957 uint32_t inputIndex,
958 int32_t& outValue,
959 const HalModel& model,
960 const ConversionData& data)
961{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100962 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100963}
964
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100965template<typename HalPolicy,
966 typename HalOperation = typename HalPolicy::Operation,
967 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100968bool GetInputFloat32(const HalOperation& operation,
969 uint32_t inputIndex,
970 float& outValue,
971 const HalModel& model,
972 const ConversionData& data)
973{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100974 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100975}
976
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100977template<typename HalPolicy,
978 typename HalOperation = typename HalPolicy::Operation,
979 typename HalOperandType = typename HalPolicy::OperandType,
980 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100981bool GetInputActivationFunctionImpl(const HalOperation& operation,
982 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100983 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100984 ActivationFn& outActivationFunction,
985 const HalModel& model,
986 const ConversionData& data)
987{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100988 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100989 {
990 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
991 __func__,
992 toString(type).c_str(),
Sadik Armagan188675f2021-02-12 17:16:42 +0000993 toString(HalOperandType::INT32).c_str(),
994 toString(HalOperandType::TENSOR_INT32).c_str());
arovir01b0717b52018-09-05 17:03:25 +0100995 }
996
997 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100998 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100999 {
1000 return Fail("%s: failed to get activation input value", __func__);
1001 }
1002 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
1003 return true;
1004}
1005
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001006template<typename HalPolicy,
1007 typename HalOperation = typename HalPolicy::Operation,
1008 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001009bool GetInputActivationFunction(const HalOperation& operation,
1010 uint32_t inputIndex,
1011 ActivationFn& outActivationFunction,
1012 const HalModel& model,
1013 const ConversionData& data)
1014{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001015 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1016 inputIndex,
1017 HalPolicy::OperandType::INT32,
1018 outActivationFunction,
1019 model,
1020 data);
arovir01b0717b52018-09-05 17:03:25 +01001021}
1022
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001023template<typename HalPolicy,
1024 typename HalOperation = typename HalPolicy::Operation,
1025 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001026bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
1027 uint32_t inputIndex,
1028 ActivationFn& outActivationFunction,
1029 const HalModel& model,
1030 const ConversionData& data)
1031{
1032 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001033 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1034 inputIndex,
1035 HalPolicy::OperandType::INT32,
1036 outActivationFunction,
1037 model,
1038 data);
arovir01b0717b52018-09-05 17:03:25 +01001039}
1040
1041
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001042template<typename HalPolicy,
1043 typename HalOperation = typename HalPolicy::Operation,
1044 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001045bool GetOptionalInputActivation(const HalOperation& operation,
1046 uint32_t inputIndex,
1047 ActivationFn& activationFunction,
1048 const HalModel& model,
1049 const ConversionData& data)
1050{
1051 if (operation.inputs.size() <= inputIndex)
1052 {
1053 activationFunction = ActivationFn::kActivationNone;
1054 }
1055 else
1056 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001057 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001058 {
1059 return Fail("%s: Operation has invalid inputs", __func__);
1060 }
1061 }
1062 return true;
1063}
1064
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001065template<typename HalPolicy,
1066 typename ConvolutionDescriptor,
1067 typename HalOperation = typename HalPolicy::Operation,
1068 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001069bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1070 uint32_t dilationXIndex,
1071 ConvolutionDescriptor& descriptor,
1072 const HalModel& model,
1073 const ConversionData& data)
1074{
1075 bool success = true;
1076 if (operation.inputs.size() >= dilationXIndex + 2)
1077 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001078 success &= GetInputScalar<HalPolicy>(operation,
1079 dilationXIndex,
1080 HalPolicy::OperandType::INT32,
1081 descriptor.m_DilationX,
1082 model,
1083 data);
1084 success &= GetInputScalar<HalPolicy>(operation,
1085 dilationXIndex + 1,
1086 HalPolicy::OperandType::INT32,
1087 descriptor.m_DilationY,
1088 model,
1089 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001090 }
1091
1092 return success;
1093}
1094
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001095template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001096 typename HalOperation = typename HalPolicy::Operation,
1097 typename HalModel = typename HalPolicy::Model>
1098bool GetOptionalBool(const HalOperation& operation,
1099 uint32_t inputIndex,
1100 const HalModel& model,
1101 const ConversionData& data)
1102{
1103 using HalOperand = typename HalPolicy::Operand;
1104
1105 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1106 if (!operand)
1107 {
1108 return false;
1109 }
1110
1111 if (!IsBool(*operand))
1112 {
1113 return false;
1114 }
1115
1116 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1117 if (!valueAddress)
1118 {
1119 return false;
1120 }
1121
1122 if (*(static_cast<const bool*>(valueAddress)))
1123 {
1124 return true;
1125 }
1126 else
1127 {
1128 return false;
1129 }
1130}
1131
1132template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001133 typename HalOperand = typename HalPolicy::Operand,
1134 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001135bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001136 std::vector<int32_t>& outValues,
1137 const HalModel& model,
1138 const ConversionData& data)
1139{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001140 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001141 {
1142 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1143 }
1144
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001145 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001146 if (!startAddress)
1147 {
1148 return Fail("%s: failed to get operand address", __func__, operand.type);
1149 }
1150
1151 // Check number of bytes is sensible
1152 const uint32_t numBytes = operand.location.length;
1153 if (numBytes % sizeof(int32_t) != 0)
1154 {
1155 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1156 __func__, numBytes, sizeof(int32_t));
1157 }
1158
1159 outValues.resize(numBytes / sizeof(int32_t));
1160 memcpy(outValues.data(), startAddress, numBytes);
1161 return true;
1162}
1163
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001164template<typename HalPolicy,
1165 typename HalOperation = typename HalPolicy::Operation,
1166 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001167bool GetInputPaddingScheme(const HalOperation& operation,
1168 uint32_t inputIndex,
1169 PaddingScheme& outPaddingScheme,
1170 const HalModel& model,
1171 const ConversionData& data)
1172{
1173 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001174 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001175 {
1176 return Fail("%s: failed to get padding scheme input value", __func__);
1177 }
1178
1179 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1180 return true;
1181}
1182
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001183template<typename HalPolicy,
1184 typename HalOperation = typename HalPolicy::Operation,
1185 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001186LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1187 uint32_t inputIndex,
1188 const HalModel& model,
1189 ConversionData& data)
1190{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001191 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001192 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001193 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1194
1195 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001196 if (!operand)
1197 {
1198 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1199 return LayerInputHandle();
1200 }
1201
1202 if (!IsOperandTypeSupportedForTensors(operand->type))
1203 {
1204 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1205 return LayerInputHandle();
1206 }
1207
Sadik Armagan44bcc022019-06-18 17:21:36 +01001208 try
arovir01b0717b52018-09-05 17:03:25 +01001209 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001210 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001211 if (IsDynamicTensor(operandTensorInfo))
1212 {
1213 Fail("%s: dynamic input tensors are not supported", __func__);
1214 return LayerInputHandle();
1215 }
arovir01b0717b52018-09-05 17:03:25 +01001216
Sadik Armagan44bcc022019-06-18 17:21:36 +01001217 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001218 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001219 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001220 {
1221 // NOTE: We must check whether we can support the input tensor on at least one
1222 // of the provided backends; otherwise we cannot convert the operation
1223 bool isInputSupported = false;
1224 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1225 IsInputSupported,
1226 data.m_Backends,
1227 isInputSupported,
1228 operandTensorInfo);
1229
1230 if (!isInputSupported)
1231 {
1232 Fail("%s: unsupported input tensor", __func__);
1233 return LayerInputHandle();
1234 }
1235
James Ward4e22f602020-10-20 15:50:33 +01001236 [[clang::fallthrough]]; // intentional fallthrough
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001237 }
1238 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001239 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001240 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001241 // The tensor is either an operand internal to the model, or a model input.
1242 // It can be associated with an ArmNN output slot for an existing layer.
1243
1244 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1245 const uint32_t operandIndex = operation.inputs[inputIndex];
1246 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001247 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001248 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001249 case HalOperandLifeTime::CONSTANT_REFERENCE:
1250 {
1251 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1252 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1253 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001254 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001255 bool isSupported = false;
1256 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1257 IsConstantSupported,
1258 data.m_Backends,
1259 isSupported,
1260 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001261 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001262 {
1263 return LayerInputHandle();
1264 }
1265
1266 armnn::IConnectableLayer* constantLayer =
1267 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1268 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
Matthew Sloyan56c249c2021-08-09 12:49:23 +01001269 armnn::TensorInfo constantTensorInfo = tensorPin.GetConstTensor().GetInfo();
1270 outputSlot.SetTensorInfo(constantTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001271
Matthew Sloyan56c249c2021-08-09 12:49:23 +01001272 return LayerInputHandle(true, &outputSlot, constantTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001273 }
1274 else
1275 {
1276 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001277 return LayerInputHandle();
1278 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001279 break;
arovir01b0717b52018-09-05 17:03:25 +01001280 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001281 default:
arovir01b0717b52018-09-05 17:03:25 +01001282 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001283 // Unsupported lifetime for an input tensor
1284 Fail("%s: unsupported lifetime for input tensor: %s",
1285 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001286 return LayerInputHandle();
1287 }
arovir01b0717b52018-09-05 17:03:25 +01001288 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001289 }
1290 catch (UnsupportedOperand<HalOperandType>& e)
1291 {
1292 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1293 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001294 }
1295}
1296
Kevin May42477c12020-03-26 13:34:14 +00001297
1298#ifdef ARMNN_ANDROID_NN_V1_3
1299template<typename HalPolicy>
1300LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1301 uint32_t inputIndex,
1302 const::android::hardware::neuralnetworks::V1_3::Model& model,
1303 ConversionData& data)
1304{
1305 using HalOperand = typename HalPolicy::Operand;
1306 using HalOperandType = typename HalPolicy::OperandType;
1307 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1308
1309 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1310 if (!operand)
1311 {
1312 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1313 return LayerInputHandle();
1314 }
1315
1316 if (!IsOperandTypeSupportedForTensors(operand->type))
1317 {
1318 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1319 return LayerInputHandle();
1320 }
1321
1322 try
1323 {
1324 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Finn Williams9a044412020-08-17 19:08:35 +01001325
Kevin May42477c12020-03-26 13:34:14 +00001326 if (IsDynamicTensor(operandTensorInfo))
1327 {
Finn Williams291a16b2020-08-19 22:54:00 +01001328 data.m_DynamicInputsEncountered = true;
1329
Finn Williams9a044412020-08-17 19:08:35 +01001330 const uint32_t operandIndex = operation.inputs[inputIndex];
1331
1332 // Check if the dynamic input tensors have been inferred by one of the previous layers
1333 // If not we can't support them
Finn Williams291a16b2020-08-19 22:54:00 +01001334 if (data.m_OutputSlotForOperand.size() >= operandIndex && data.m_OutputSlotForOperand[operandIndex])
Finn Williams9a044412020-08-17 19:08:35 +01001335 {
1336 operandTensorInfo = data.m_OutputSlotForOperand[operandIndex]->GetTensorInfo();
1337 }
1338 else
1339 {
1340 Fail("%s: Type 2 dynamic input tensors are not supported", __func__);
1341 return LayerInputHandle();
1342 }
Kevin May42477c12020-03-26 13:34:14 +00001343 }
1344
1345 switch (operand->lifetime)
1346 {
1347 case HalOperandLifeTime::SUBGRAPH_INPUT:
1348 {
1349 // NOTE: We must check whether we can support the input tensor on at least one
1350 // of the provided backends; otherwise we cannot convert the operation
1351 bool isInputSupported = false;
1352 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1353 IsInputSupported,
1354 data.m_Backends,
1355 isInputSupported,
1356 operandTensorInfo);
1357
1358 if (!isInputSupported)
1359 {
1360 Fail("%s: unsupported input tensor", __func__);
1361 return LayerInputHandle();
1362 }
1363
James Ward4e22f602020-10-20 15:50:33 +01001364 [[clang::fallthrough]]; // intentional fallthrough
Kevin May42477c12020-03-26 13:34:14 +00001365 }
1366 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1367 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1368 {
1369 // The tensor is either an operand internal to the model, or a model input.
1370 // It can be associated with an ArmNN output slot for an existing layer.
1371
1372 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1373 const uint32_t operandIndex = operation.inputs[inputIndex];
1374 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1375 }
1376 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1377 case HalOperandLifeTime::CONSTANT_REFERENCE:
1378 {
1379 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1380 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1381 if (tensorPin.IsValid())
1382 {
1383 bool isSupported = false;
1384 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1385 IsConstantSupported,
1386 data.m_Backends,
1387 isSupported,
1388 tensorPin.GetConstTensor().GetInfo());
1389 if (!isSupported)
1390 {
1391 return LayerInputHandle();
1392 }
1393
1394 armnn::IConnectableLayer* constantLayer =
1395 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1396 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
Matthew Sloyan56c249c2021-08-09 12:49:23 +01001397 armnn::TensorInfo constantTensorInfo = tensorPin.GetConstTensor().GetInfo();
1398 outputSlot.SetTensorInfo(constantTensorInfo);
Kevin May42477c12020-03-26 13:34:14 +00001399
Matthew Sloyan56c249c2021-08-09 12:49:23 +01001400 return LayerInputHandle(true, &outputSlot, constantTensorInfo);
Kevin May42477c12020-03-26 13:34:14 +00001401 }
1402 else
1403 {
1404 Fail("%s: invalid operand tensor", __func__);
1405 return LayerInputHandle();
1406 }
1407 break;
1408 }
1409 default:
1410 {
1411 // Unsupported lifetime for an input tensor
1412 Fail("%s: unsupported lifetime for input tensor: %s",
1413 __func__, toString(operand->lifetime).c_str());
1414 return LayerInputHandle();
1415 }
1416 }
1417 }
1418 catch (UnsupportedOperand<HalOperandType>& e)
1419 {
1420 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1421 return LayerInputHandle();
1422 }
1423}
1424#endif
1425
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001426template<typename HalPolicy,
1427 typename HalOperation = typename HalPolicy::Operation,
1428 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001429bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1430 uint32_t operationOutputIndex,
1431 armnn::IConnectableLayer& layer,
1432 uint32_t layerOutputIndex,
1433 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001434 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001435 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001436 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001437 const ActivationFn& activationFunction = ActivationFn::kActivationNone,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001438 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001439{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001440 using HalOperand = typename HalPolicy::Operand;
1441
1442 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001443 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1444 {
1445 return false;
1446 }
1447
1448 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001449 if (overrideOutputInfo == nullptr)
1450 {
1451 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1452 }
1453 else
1454 {
1455 outputSlot.SetTensorInfo(*overrideOutputInfo);
1456 }
1457
Finn Williamsa4983ce2020-07-23 12:55:12 +01001458 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001459 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001460 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001461 // Type one dynamic tensors require the previous layer's output shape for inference
1462 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1463 {
Mike Kellye2d611e2021-10-14 12:35:58 +01001464 if (!layer.GetInputSlot(inputSlotIndex).GetConnection())
Sadik Armagandbda4b72020-09-03 11:33:07 +01001465 {
1466 return false;
1467 }
1468 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001469 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001470 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001471 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001472 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1473
Sadik Armagandbda4b72020-09-03 11:33:07 +01001474 if(!isSupported)
1475 {
1476 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1477 {
1478 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1479 }
1480 return false;
1481 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001482 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001483
Finn Williamsa4983ce2020-07-23 12:55:12 +01001484 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
Kevin Mayfcf2a152020-09-08 16:06:32 +01001485
1486 if (activationFunction != ActivationFn::kActivationNone)
1487 {
1488 const armnn::TensorInfo& activationOutputInfo = outputSlot.GetTensorInfo();
1489 armnn::IConnectableLayer* const endLayer = ProcessActivation(activationOutputInfo, activationFunction,
1490 &layer, data);
1491
1492 if (!endLayer)
1493 {
1494 return Fail("%s: ProcessActivation failed", __func__);
1495 }
1496
1497 armnn::IOutputSlot& activationOutputSlot = endLayer->GetOutputSlot(layerOutputIndex);
1498 data.m_OutputSlotForOperand[operandIndex] = &activationOutputSlot;
1499 }
1500 else
1501 {
1502 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1503 }
Finn Williamsa4983ce2020-07-23 12:55:12 +01001504
Mike Kellyb5fdf382019-06-11 16:35:25 +01001505 return true;
1506}
1507
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001508template<typename HalPolicy,
1509 typename HalOperation = typename HalPolicy::Operation,
1510 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001511armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1512 uint32_t inputIndex,
1513 const HalModel& model,
1514 ConversionData& data)
1515{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001516 using HalOperand = typename HalPolicy::Operand;
1517
1518 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001519 if (!operand)
1520 {
1521 return armnn::DataLayout::NHWC;
1522 }
1523
1524 if (!IsBool(*operand))
1525 {
1526 return armnn::DataLayout::NHWC;
1527 }
1528
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001529 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001530 if (!valueAddress)
1531 {
1532 return armnn::DataLayout::NHWC;
1533 }
1534
1535 if (*(static_cast<const bool*>(valueAddress)))
1536 {
1537 return armnn::DataLayout::NCHW;
1538 }
1539 else
1540 {
1541 return armnn::DataLayout::NHWC;
1542 }
1543}
1544
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001545template<typename HalPolicy,
1546 typename HalOperation = typename HalPolicy::Operation,
1547 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001548bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1549 uint32_t outputIndex,
1550 armnn::IConnectableLayer& layer,
1551 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001552 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001553 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001554 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
1555 const ActivationFn& activationFunction = ActivationFn::kActivationNone)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001556{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001557 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1558 outputIndex,
1559 layer,
1560 outputIndex,
1561 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001562 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001563 overrideOutputInfo,
Kevin Mayfcf2a152020-09-08 16:06:32 +01001564 validateFunc,
1565 activationFunction);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001566}
1567
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001568template<typename HalPolicy,
1569 typename HalOperation = typename HalPolicy::Operation,
1570 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001571bool ConvertToActivation(const HalOperation& operation,
1572 const char* operationName,
1573 const armnn::ActivationDescriptor& activationDesc,
1574 const HalModel& model,
1575 ConversionData& data)
1576{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001577 using HalOperand = typename HalPolicy::Operand;
1578
1579 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001580 if (!input.IsValid())
1581 {
1582 return Fail("%s: Input 0 is invalid", operationName);
1583 }
1584
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001585 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001586 if (!outputOperand)
1587 {
1588 return false;
1589 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001590
1591 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001592
1593 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001594
1595 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1596 {
1597 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1598 IsActivationSupported,
1599 data.m_Backends,
1600 isSupported,
1601 input.GetTensorInfo(),
1602 outInfo,
1603 activationDesc);
1604 };
1605
1606 if(IsDynamicTensor(outInfo))
1607 {
1608 isSupported = AreDynamicTensorsSupported();
1609 }
1610 else
1611 {
1612 validateFunc(outInfo, isSupported);
1613 }
1614
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001615 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001616 {
1617 return false;
1618 }
1619
1620 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Mike Kellye2d611e2021-10-14 12:35:58 +01001621 if (!layer)
1622 {
1623 return Fail("%s: Could not add the ActivationLayer", __func__);
1624 }
arovir01b0717b52018-09-05 17:03:25 +01001625 input.Connect(layer->GetInputSlot(0));
1626
Finn Williamsa4983ce2020-07-23 12:55:12 +01001627 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001628}
1629
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001630template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001631 typename HalOperation = typename HalPolicy::Operation,
1632 typename HalModel = typename HalPolicy::Model>
1633bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1634{
1635 armnn::ActivationDescriptor desc;
1636 desc.m_Function = armnn::ActivationFunction::ReLu;
1637
1638 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1639}
1640
1641template<typename HalPolicy,
1642 typename HalOperation = typename HalPolicy::Operation,
1643 typename HalModel = typename HalPolicy::Model>
1644bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1645{
1646 armnn::ActivationDescriptor desc;
1647 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1648 desc.m_A = 1.0f;
1649 desc.m_B = -1.0f;
1650
1651 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1652}
1653
1654template<typename HalPolicy,
1655 typename HalOperation = typename HalPolicy::Operation,
1656 typename HalModel = typename HalPolicy::Model>
1657bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1658{
1659 armnn::ActivationDescriptor desc;
1660 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1661 desc.m_A = 6.0f;
1662
1663 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1664}
1665
1666template<typename HalPolicy,
1667 typename HalOperation = typename HalPolicy::Operation,
1668 typename HalModel = typename HalPolicy::Model>
1669bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1670{
1671 armnn::ActivationDescriptor desc;
1672 desc.m_Function = armnn::ActivationFunction::TanH;
1673 desc.m_A = 1.0f; // android nn does not support tanH parameters
1674 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1675
1676 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1677}
1678
1679template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001680 typename HalOperation = typename HalPolicy::Operation,
1681 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001682bool ConvertPaddings(const HalOperation& operation,
1683 const HalModel& model,
1684 ConversionData& data,
1685 unsigned int rank,
1686 armnn::PadDescriptor& padDescriptor)
1687{
1688 using HalOperand = typename HalPolicy::Operand;
1689
1690 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1691 if (!paddingsOperand)
1692 {
1693 return Fail("%s: Could not read paddings operand", __func__);
1694 }
1695
1696 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1697 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1698 {
1699 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1700 }
1701
1702 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001703 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1704 {
1705 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1706 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001707
1708 // add padding for each dimension of input tensor.
1709 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1710 {
1711 int paddingBeforeInput = paddings[i];
1712 int paddingAfterInput = paddings[i + 1];
1713
1714 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1715 {
1716 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1717 }
1718
1719 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1720 }
1721
1722 return true;
1723}
1724
1725template<typename HalPolicy,
1726 typename HalOperation = typename HalPolicy::Operation,
1727 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001728bool ConvertPooling2d(const HalOperation& operation,
1729 const char* operationName,
1730 armnn::PoolingAlgorithm poolType,
1731 const HalModel& model,
1732 ConversionData& data)
1733{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001734 using HalOperand = typename HalPolicy::Operand;
1735 using HalOperandType = typename HalPolicy::OperandType;
1736
1737 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001738 if (!input.IsValid())
1739 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001740 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001741 }
1742
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001743 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001744 if (!output)
1745 {
1746 return Fail("%s: Could not read output 0", __func__);
1747 }
1748
1749 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1750 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1751
arovir01b0717b52018-09-05 17:03:25 +01001752 armnn::Pooling2dDescriptor desc;
1753 desc.m_PoolType = poolType;
1754 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001755 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001756
1757 ActivationFn activation;
1758
Sadik Armagan15d63e22019-07-26 16:59:35 +01001759 auto inputSize = operation.inputs.size();
1760
1761 if (inputSize >= 10)
1762 {
1763 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1764 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1765 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1766 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1767 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1768 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1769 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1770 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1771 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1772 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1773 {
1774 return Fail("%s: Operation has invalid inputs", operationName);
1775 }
1776
Kevin May42477c12020-03-26 13:34:14 +00001777 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001778 {
1779 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1780 }
1781 }
1782 else
arovir01b0717b52018-09-05 17:03:25 +01001783 {
1784 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1785 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001786 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1787 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1788 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1789 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1790 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1791 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001792 {
1793 return Fail("%s: Operation has invalid inputs", operationName);
1794 }
1795
Kevin May42477c12020-03-26 13:34:14 +00001796 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001797 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001798 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001799 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001800
1801 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1802 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1803 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1804
1805 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1806 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001807 }
1808
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001809 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001810
1811 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1812 {
1813 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1814 IsPooling2dSupported,
1815 data.m_Backends,
1816 isSupported,
1817 inputInfo,
1818 outputInfo,
1819 desc);
1820
1821 };
1822
1823 if(IsDynamicTensor(outputInfo))
1824 {
1825 isSupported = AreDynamicTensorsSupported();
1826 }
1827 else
1828 {
1829 validateFunc(outputInfo, isSupported);
1830 }
1831
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001832 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001833 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001834 return false;
arovir01b0717b52018-09-05 17:03:25 +01001835 }
arovir01b0717b52018-09-05 17:03:25 +01001836
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001837 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1838 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001839 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001840 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001841 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001842
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001843 input.Connect(pooling2dLayer->GetInputSlot(0));
1844
Finn Williamsa4983ce2020-07-23 12:55:12 +01001845 if (!isSupported)
1846 {
1847 return false;
1848 }
1849
Kevin Mayfcf2a152020-09-08 16:06:32 +01001850 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *pooling2dLayer, model,
1851 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001852}
1853
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001854template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001855 typename HalOperation = typename HalPolicy::Operation,
1856 typename HalModel = typename HalPolicy::Model>
1857bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001858{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001859 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001860
1861 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1862 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1863
1864 if (!input0.IsValid() || !input1.IsValid())
1865 {
1866 return Fail("%s: Operation has invalid inputs", __func__);
1867 }
1868
1869 // The FuseActivation parameter is always the input index 2
1870 // and it should be optional
1871 ActivationFn activationFunction;
1872 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1873 {
1874 return Fail("%s: Operation has invalid inputs", __func__);
1875 }
1876
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001877 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001878 if (!outputOperand)
1879 {
1880 return false;
1881 }
1882
1883 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1884 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1885
1886 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001887
1888 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001889 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1890 {
1891 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1892 IsAdditionSupported,
1893 data.m_Backends,
1894 isSupported,
1895 inputInfo0,
1896 inputInfo1,
1897 outputInfo);
1898 };
1899
1900 if(!IsDynamicTensor(outputInfo))
1901 {
1902 validateFunc(outputInfo, isSupported);
1903 }
1904 else
1905 {
1906 isSupported = AreDynamicTensorsSupported();
1907 }
1908
Mike Kelly46272802019-08-14 17:00:48 +01001909 if (!isSupported)
1910 {
1911 return false;
1912 }
1913
1914 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01001915
Kevin Mayfcf2a152020-09-08 16:06:32 +01001916 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1917 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01001918 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01001919 return false;
1920 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01001921
Kevin Mayfcf2a152020-09-08 16:06:32 +01001922 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
1923 data, nullptr, validateFunc, activationFunction);
1924
Mike Kelly46272802019-08-14 17:00:48 +01001925}
1926
1927template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001928 typename HalOperation = typename HalPolicy::Operation,
1929 typename HalModel = typename HalPolicy::Model>
1930bool ConvertArgMinMax(const HalOperation& operation,
1931 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001932 ConversionData& data,
1933 armnn::ArgMinMaxFunction argMinMaxFunction)
1934{
1935 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1936
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001937 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001938 using HalOperandType = typename HalPolicy::OperandType;
1939
1940 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1941
1942 if (!input0.IsValid())
1943 {
1944 return Fail("%s: Operation has invalid inputs", __func__);
1945 }
1946
1947 int32_t axis;
1948 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1949 {
1950 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1951 }
1952
1953 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1954 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1955
1956 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1957 {
1958 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1959 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1960 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1961 return Fail("%s: Axis must be in range [-n, n)", __func__);
1962 }
1963
1964 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1965 if (!output)
1966 {
1967 return Fail("%s: Could not read output 0", __func__);
1968 }
1969
1970 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1971
1972 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001973
1974 armnn::ArgMinMaxDescriptor descriptor;
1975 descriptor.m_Function = argMinMaxFunction;
1976 descriptor.m_Axis = axis;
1977
1978 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001979
1980 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1981 {
1982 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1983 IsArgMinMaxSupported,
1984 data.m_Backends,
1985 isSupported,
1986 inputInfo0,
1987 outputInfo,
1988 descriptor);
1989 };
1990
1991 if(IsDynamicTensor(outputInfo))
1992 {
1993 isSupported = AreDynamicTensorsSupported();
1994 }
1995 else
1996 {
1997 validateFunc(outputInfo, isSupported);
1998 }
1999
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00002000 if (!isSupported)
2001 {
2002 return false;
2003 }
2004
2005 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01002006 if (!layer)
2007 {
2008 return Fail("%s: Could not add the ArgMinMaxLayer", __func__);
2009 }
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00002010 input0.Connect(layer->GetInputSlot(0));
2011
Finn Williamsa4983ce2020-07-23 12:55:12 +01002012 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00002013}
2014
2015template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002016 typename HalOperation = typename HalPolicy::Operation,
2017 typename HalModel = typename HalPolicy::Model>
2018bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01002019{
Keith Davis6e4081f2020-09-03 13:17:21 +01002020 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01002021 using HalOperandType = typename HalPolicy::OperandType;
2022
2023 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
2024 if (operation.inputs.size() <= 1)
2025 {
2026 return Fail("%s: Operation has insufficient arguments", __func__);
2027 }
2028
2029 // Get inputs and outputs
2030 const std::size_t numInputTensors = operation.inputs.size() - 1;
2031
2032 int32_t concatDim;
2033 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
2034 {
2035 return Fail("%s: Operation has invalid inputs", __func__);
2036 }
2037
2038 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2039 if (!outputOperand)
2040 {
2041 return Fail("%s: Operation has no outputs", __func__);
2042 }
2043
Keith Davis6e4081f2020-09-03 13:17:21 +01002044 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
2045 armnn::TensorShape outputShape = outputInfo.GetShape();
2046 const bool isDynamicTensor = IsDynamicTensor(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002047 //
2048 // handle negative concat dims along the lines of tensorflow as described here:
2049 // https://www.tensorflow.org/api_docs/python/tf/concat
2050 // "negative axis refers to axis + rank(values)-th dimension"
2051 //
2052 if (concatDim < 0)
2053 {
2054 concatDim += outputShape.GetNumDimensions();
2055 }
2056
2057 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2058 {
2059 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2060 }
2061
2062 std::vector<LayerInputHandle> inputHandles;
2063 std::vector<armnn::TensorShape> inputShapes;
2064
2065 inputHandles.reserve(numInputTensors);
2066 inputShapes.reserve(numInputTensors);
2067
Keith Davis6e4081f2020-09-03 13:17:21 +01002068 bool inputsHaveBeenReshaped = false;
2069 unsigned int tensorDimensionsAdded = 0;
Mike Kellyb8805202019-07-31 17:25:43 +01002070 for (uint32_t i = 0; i < numInputTensors; ++i)
2071 {
2072 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2073 if (!operand)
2074 {
2075 return Fail("%s: Operation has invalid inputs", __func__);
2076 }
2077
Teresa Charlin3b959602019-10-31 17:05:47 +00002078 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2079 if (!operandInputHandle.IsValid())
2080 {
2081 return Fail("%s: Operation has invalid inputs", __func__);
2082 }
Mike Kellyb8805202019-07-31 17:25:43 +01002083
Keith Davis6e4081f2020-09-03 13:17:21 +01002084 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002085 if (operandShape.GetNumDimensions() == 0)
2086 {
2087 return Fail("%s: Operands with rank 0 are not supported", __func__);
2088 }
2089
2090 if (RequiresReshape(operandShape))
2091 {
2092 inputsHaveBeenReshaped = true;
2093
2094 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2095
2096 // Expand the tensor to three dimensions
2097 if (operandShape.GetNumDimensions() == 2)
2098 {
2099 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2100 tensorDimensionsAdded = 1;
2101 }
2102 else
2103 {
2104 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2105 tensorDimensionsAdded = 2;
2106 }
2107
Kevin Mayaed08ac2019-12-12 16:33:31 +00002108 armnn::ReshapeDescriptor reshapeDescriptor;
2109 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2110
2111 bool isSupported = false;
2112 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2113 IsReshapeSupported,
2114 data.m_Backends,
2115 isSupported,
2116 operandInputHandle.GetTensorInfo(),
2117 reshapeInfo,
2118 reshapeDescriptor);
Keith Davis6e4081f2020-09-03 13:17:21 +01002119
Kevin Mayaed08ac2019-12-12 16:33:31 +00002120 if (!isSupported)
2121 {
2122 return false;
2123 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002124 armnn::IConnectableLayer& newReshape = AddReshapeLayer(*data.m_Network, operandInputHandle, reshapeInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002125
2126 // Point to the reshape operation rather then the input operation
Keith Davis6e4081f2020-09-03 13:17:21 +01002127 operandShape = reshapeInfo.GetShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002128 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2129 }
2130
2131 inputShapes.emplace_back(operandShape);
2132 inputHandles.emplace_back(operandInputHandle);
2133
2134 if (!inputHandles.back().IsValid())
2135 {
2136 return Fail("%s: Operation has invalid inputs", __func__);
2137 }
2138 }
2139
Mike Kellye2d611e2021-10-14 12:35:58 +01002140 if (inputShapes.size() != inputHandles.size())
2141 {
2142 return Fail("%s: invalid model input shapes size doesn't match input handles sise: %i != %i", __func__,
2143 inputShapes.size(), inputHandles.size());
2144 }
Mike Kellyb8805202019-07-31 17:25:43 +01002145
2146 if (inputsHaveBeenReshaped)
2147 {
2148 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2149 concatDim += tensorDimensionsAdded;
2150
2151 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2152 if (tensorDimensionsAdded == 1)
2153 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002154 if (IsDynamicTensor(outputInfo))
2155 {
2156 outputShape = armnn::TensorShape({1, 0, 0}, {true, false, false});
2157 }
2158 else
2159 {
2160 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2161 }
Mike Kellyb8805202019-07-31 17:25:43 +01002162 }
2163 else if (tensorDimensionsAdded == 2)
2164 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002165 if (IsDynamicTensor(outputInfo))
2166 {
2167 outputShape = armnn::TensorShape({1, 1, 0}, {true, true, false});
2168 }
2169 else
2170 {
2171 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2172 }
Mike Kellyb8805202019-07-31 17:25:43 +01002173 }
2174 }
2175
2176 // Check if permutations is required and get the pair of permutations required for the concatenation.
2177 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2178 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
Keith Davis6e4081f2020-09-03 13:17:21 +01002179 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
Keith Davis6e4081f2020-09-03 13:17:21 +01002180 bool needPermute = CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(),
2181 concatDim,
2182 permutationPair);
Mike Kellyb8805202019-07-31 17:25:43 +01002183
Keith Davis6e4081f2020-09-03 13:17:21 +01002184 // Only relevant to static tensors as dynamic output tensors will be transposed as a result of inferring from input
2185 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002186 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002187 if (needPermute)
2188 {
2189 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
2190 }
2191
2192 outputInfo.SetShape(outputShape);
Mike Kellyb8805202019-07-31 17:25:43 +01002193 }
Mike Kellyb8805202019-07-31 17:25:43 +01002194 // this is no-op for identity swizzles, otherwise it replaces both
2195 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002196 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002197 {
2198 return false;
2199 }
Mike Kellyb8805202019-07-31 17:25:43 +01002200
2201 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2202 armnn::OriginsDescriptor concatDescriptor;
2203
2204 try
2205 {
2206 // The concat descriptor is always created across the only supported concat dimension
2207 // 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 +01002208 concatDescriptor = armnn::CreateDescriptorForConcatenation(inputShapes.begin(),
2209 inputShapes.end(),
2210 concatDim);
2211 } catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002212 {
2213 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2214 }
2215
2216 // Validate the output shape is correct given the input shapes based on the
2217 // 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 +01002218 if (!isDynamicTensor)
Mike Kellyb8805202019-07-31 17:25:43 +01002219 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002220 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2221 {
2222 return Fail("%s: Error validating the output shape for concat", __func__);
2223 }
Mike Kellyb8805202019-07-31 17:25:43 +01002224 }
2225
2226 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2227 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
Keith Davis6e4081f2020-09-03 13:17:21 +01002228 [](const LayerInputHandle& h)->const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
Mike Kellyb8805202019-07-31 17:25:43 +01002229
Keith Davis6e4081f2020-09-03 13:17:21 +01002230 bool isSupported = false;
2231 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported){
2232 FORWARD_LAYER_SUPPORT_FUNC(__func__, IsConcatSupported, data.m_Backends, isSupported, inputTensorInfos,
2233 outputInfo, concatDescriptor);
2234 };
2235
2236 if (!isDynamicTensor)
2237 {
2238 validateFunc(outputInfo, isSupported);
2239 }
2240 else
2241 {
2242 isSupported = AreDynamicTensorsSupported();
2243 }
2244
Mike Kellyb8805202019-07-31 17:25:43 +01002245 if (!isSupported)
2246 {
2247 return false;
2248 }
2249
2250 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01002251 if (!layer)
2252 {
2253 return Fail("%s: Could not add the ConcatLayer", __func__);
2254 }
Mike Kellyb8805202019-07-31 17:25:43 +01002255 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
Mike Kellyb8805202019-07-31 17:25:43 +01002256 // Connect inputs to the layer
2257 const int numInputSlots = layer->GetNumInputSlots();
Mike Kellye2d611e2021-10-14 12:35:58 +01002258
2259 if (static_cast<std::size_t>(numInputSlots) != inputHandles.size())
2260 {
2261 return Fail("%s: invalid model input slots size doesn't match input handles sise: %i != %i", __func__,
2262 static_cast<std::size_t>(numInputSlots), inputHandles.size());
2263 }
Mike Kellyb8805202019-07-31 17:25:43 +01002264 for (int i = 0; i < numInputSlots; ++i)
2265 {
2266 // connect the input directly to the merge (concat) layer
2267 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2268 }
2269
Keith Davis6e4081f2020-09-03 13:17:21 +01002270 // Transpose the output shape
2271 auto transposeOutputShape = [&](){
Mike Kelly4a956582020-02-28 10:32:09 +00002272 armnn::TransposeDescriptor transposeDesc;
2273 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002274 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2275 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2276 permutationPair.second);
Keith Davis6e4081f2020-09-03 13:17:21 +01002277 isSupported = false;
Kevin Mayaed08ac2019-12-12 16:33:31 +00002278 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002279 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002280 data.m_Backends,
2281 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002282 inputTransposeInfo,
2283 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002284 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002285 if (!isSupported)
2286 {
2287 return false;
2288 }
Mike Kellyb8805202019-07-31 17:25:43 +01002289 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Keith Davis6e4081f2020-09-03 13:17:21 +01002290 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network, layer->GetOutputSlot(0),
Mike Kelly4a956582020-02-28 10:32:09 +00002291 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002292 layer = &deswizzleLayer;
Keith Davis6e4081f2020-09-03 13:17:21 +01002293
2294 return true;
2295 };
2296
2297 if (needPermute && !isDynamicTensor)
2298 {
2299 transposeOutputShape();
Mike Kellyb8805202019-07-31 17:25:43 +01002300 }
2301
2302 if (inputsHaveBeenReshaped)
2303 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002304 if (isDynamicTensor)
2305 {
2306 // Infer the output shapes of concat if outputs are type 1 dynamic
Mike Kellye2d611e2021-10-14 12:35:58 +01002307 if (!layer->GetOutputSlot(0).IsTensorInfoSet())
2308 {
2309 return Fail("%s: TensorInfo is not set", __func__);
2310 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002311 if (!ValidateConcatOutputShape(inputShapes,
2312 layer->GetOutputSlot(0).GetTensorInfo().GetShape(),
2313 concatDim))
2314 {
2315 return Fail("%s: Error validating the output shape for concat", __func__);
2316 }
2317 transposeOutputShape();
2318 }
2319
Mike Kellyb8805202019-07-31 17:25:43 +01002320 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Mike Kellyb8805202019-07-31 17:25:43 +01002321 // Undo the reshape knowing the amount of dimensions added
2322 if (tensorDimensionsAdded == 1)
2323 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002324 afterConcatInfo.SetShape(
2325 armnn::TensorShape({afterConcatInfo.GetShape()[1], afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002326 }
2327 else if (tensorDimensionsAdded == 2)
2328 {
Keith Davis6e4081f2020-09-03 13:17:21 +01002329 afterConcatInfo.SetShape(armnn::TensorShape({afterConcatInfo.GetShape()[2]}));
Mike Kellyb8805202019-07-31 17:25:43 +01002330 }
2331
Kevin Mayaed08ac2019-12-12 16:33:31 +00002332 armnn::ReshapeDescriptor reshapeDescriptor;
2333 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
Keith Davis6e4081f2020-09-03 13:17:21 +01002334 armnn::TensorInfo concatInfo = layer->GetOutputSlot(0).GetTensorInfo();
Kevin Mayaed08ac2019-12-12 16:33:31 +00002335
Keith Davis6e4081f2020-09-03 13:17:21 +01002336 isSupported = false;
2337 auto validateReshapeFunc = [&](const armnn::TensorInfo& afterConcatInfo, bool& isSupported){
2338 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2339 IsReshapeSupported,
2340 data.m_Backends,
2341 isSupported,
2342 concatInfo,
2343 afterConcatInfo,
2344 reshapeDescriptor);
2345 };
2346
2347 if (!IsDynamicTensor(afterConcatInfo))
2348 {
2349 validateReshapeFunc(afterConcatInfo, isSupported);
2350 }
2351 else
2352 {
2353 isSupported = AreDynamicTensorsSupported();
2354 }
2355
Kevin Mayaed08ac2019-12-12 16:33:31 +00002356 if (!isSupported)
2357 {
2358 return false;
2359 }
Keith Davis6e4081f2020-09-03 13:17:21 +01002360 layer = &AddReshapeLayer(*data.m_Network, layer->GetOutputSlot(0), afterConcatInfo);
2361 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
2362 0,
2363 *layer,
2364 model,
2365 data,
2366 nullptr,
2367 validateReshapeFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002368 }
2369
Keith Davis6e4081f2020-09-03 13:17:21 +01002370 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kellyb8805202019-07-31 17:25:43 +01002371}
2372
2373template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002374 typename HalOperation = typename HalPolicy::Operation,
2375 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002376bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2377{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002378 using HalOperand = typename HalPolicy::Operand;
2379 using HalOperandType = typename HalPolicy::OperandType;
2380
2381 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002382 if (!input.IsValid())
2383 {
2384 return Fail("%s: Operation has invalid inputs", __func__);
2385 }
2386
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002387 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002388 if (!output)
2389 {
2390 return Fail("%s: Could not read output 0", __func__);
2391 }
2392
2393 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002394 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002395
2396 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002397 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2398 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002399
2400 if (!weightsPin.IsValid() || !biasPin.IsValid())
2401 {
2402 return Fail("%s: Operation has invalid inputs", __func__);
2403 }
2404
2405 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002406 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002407 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2408
2409 armnn::Convolution2dDescriptor desc;
2410 desc.m_DataLayout = armnn::DataLayout::NHWC;
2411 ActivationFn activation;
2412
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002413 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002414 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002415 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2416 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2417 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2418 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2419 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2420 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002421 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002422 {
2423 return Fail("%s: Operation has invalid inputs", __func__);
2424 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002425 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002426 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002427 {
2428 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002429 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2430 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2431 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002432 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002433 {
2434 return Fail("%s: Operation has invalid inputs", __func__);
2435 }
2436
2437 const uint32_t kernelX = weights.GetShape()[2];
2438 const uint32_t kernelY = weights.GetShape()[1];
2439 const uint32_t inputX = inputInfo.GetShape()[2];
2440 const uint32_t inputY = inputInfo.GetShape()[1];
2441
2442 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2443 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002444 }
2445 else
2446 {
2447 return Fail("%s: Unsupported number of operation inputs", __func__);
2448 }
2449
2450 desc.m_BiasEnabled = true;
2451 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2452
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002453 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002454 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2455 {
2456 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2457 IsConvolution2dSupported,
2458 data.m_Backends,
2459 isSupported,
2460 inputInfo,
2461 outputInfo,
2462 desc,
2463 weights.GetInfo(),
2464 biases);
2465 };
2466
2467 if(!IsDynamicTensor(outputInfo))
2468 {
2469 validateFunc(outputInfo, isSupported);
2470 }
2471 else
2472 {
2473 isSupported = AreDynamicTensorsSupported();
2474 }
2475
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002476 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002477 {
2478 return false;
2479 }
2480
2481 armnn::IConnectableLayer* startLayer =
2482 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2483
2484 if (!startLayer)
2485 {
2486 return Fail("%s: AddConvolution2dLayer failed", __func__);
2487 }
2488
Mike Kellyb5fdf382019-06-11 16:35:25 +01002489 input.Connect(startLayer->GetInputSlot(0));
2490
Kevin Mayfcf2a152020-09-08 16:06:32 +01002491 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2492 data, nullptr, validateFunc, activation);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002493}
2494
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002495template<typename HalPolicy,
2496 typename HalOperation = typename HalPolicy::Operation,
2497 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002498bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2499{
2500 using HalOperand = typename HalPolicy::Operand;
2501 using HalOperandType = typename HalPolicy::OperandType;
2502
2503 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2504 if (!input.IsValid() )
2505 {
2506 return Fail("%s: Operation has invalid inputs", __func__);
2507 }
2508
2509 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2510 unsigned int rank = inputInfo.GetNumDimensions();
2511 if (rank != 4)
2512 {
2513 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2514 }
2515
2516 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2517 if (!output)
2518 {
2519 return Fail("%s: Could not read output 0", __func__);
2520 }
2521
2522 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002523
2524 armnn::DepthToSpaceDescriptor descriptor;
2525
2526 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2527 if (descriptor.m_BlockSize <= 1)
2528 {
2529 return Fail("%s: Block size must be at least 1 in all dimensions");
2530 }
2531
2532 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002533 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002534 {
2535 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2536 }
2537
2538 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002539 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2540 {
2541 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2542 IsDepthToSpaceSupported,
2543 data.m_Backends,
2544 isSupported,
2545 inputInfo,
2546 outputInfo,
2547 descriptor);
2548 };
2549
2550 if(!IsDynamicTensor(outputInfo))
2551 {
2552 validateFunc(outputInfo, isSupported);
2553 }
2554 else
2555 {
2556 isSupported = AreDynamicTensorsSupported();
2557 }
2558
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002559 if (!isSupported)
2560 {
2561 return false;
2562 }
2563
2564 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01002565 if (!layer)
2566 {
2567 return Fail("%s: Could not add the DepthToSpaceLayer", __func__);
2568 }
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002569 input.Connect(layer->GetInputSlot(0));
2570
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002571 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002572}
2573
2574template<typename HalPolicy,
2575 typename HalOperation = typename HalPolicy::Operation,
2576 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002577bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2578{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002579 using HalOperand = typename HalPolicy::Operand;
2580 using HalOperandType = typename HalPolicy::OperandType;
2581
2582 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002583
2584 if (!input.IsValid())
2585 {
2586 return Fail("%s: Operation has invalid inputs", __func__);
2587 }
2588
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002589 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002590
2591 if (!output)
2592 {
2593 return Fail("%s: Could not read output 0", __func__);
2594 }
2595
2596 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002597 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002598
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002599 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002600 // 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 +01002601 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002602
2603 if (weightsOperand == nullptr)
2604 {
2605 return Fail("%s: Operand is invalid", __func__);
2606 }
Colm Donelanccfeb5e2021-03-30 15:30:13 +01002607 // Basic sanity check on the weights shape.
2608 // ANEURALNETWORKS_DEPTHWISE_CONV_2D specifies a 4-D tensor, of shape
2609 // [1, filter_height, filter_width, depth_out]
2610 if (weightsOperand->dimensions[0] != 1)
2611 {
2612 return Fail("%s: Filter operand dimension 0 is invalid, should be 1", __func__);
2613 }
2614
Mike Kellyb5fdf382019-06-11 16:35:25 +01002615 armnn::DepthwiseConvolution2dDescriptor desc;
2616 desc.m_DataLayout = armnn::DataLayout::NHWC;
2617
Jan Eilersa20d2b82021-04-27 09:21:08 +01002618 // The layout for weights in depthwise is [ 1, H, W, O] and it's the same in ArmNN. No need to permute anything.
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002619 const ConstTensorPin weightsPin =
2620 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2621 1,
2622 model,
Jan Eilersa20d2b82021-04-27 09:21:08 +01002623 data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002624
2625 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002626 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002627
2628 if (!weightsPin.IsValid() || !biasPin.IsValid())
2629 {
2630 return Fail("%s: Operation has invalid inputs", __func__);
2631 }
2632
2633 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2634 armnn::ConstTensor bias = biasPin.GetConstTensor();
2635 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2636
2637 ActivationFn activation;
2638
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002639 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002640 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002641 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2642 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2643 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2644 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2645 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2646 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002647 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002648 {
2649 return Fail("%s: Operation has invalid inputs", __func__);
2650 }
2651 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002652 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002653 {
2654 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002655 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2656 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2657 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002658 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002659 {
2660 return Fail("%s: Operation has invalid inputs", __func__);
2661 }
2662
Jan Eilersa20d2b82021-04-27 09:21:08 +01002663 const uint32_t kernelX = weights.GetShape()[2];
2664 const uint32_t kernelY = weights.GetShape()[1];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002665 const uint32_t inputX = inputInfo.GetShape()[2];
2666 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002667
2668 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2669 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2670 }
2671 else
2672 {
2673 return Fail("%s: Unsupported number of operation inputs", __func__);
2674 }
2675
2676 desc.m_BiasEnabled = true;
2677 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2678
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002679 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002680 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2681 {
2682 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2683 IsDepthwiseConvolutionSupported,
2684 data.m_Backends,
2685 isSupported,
2686 inputInfo,
2687 outputInfo,
2688 desc,
2689 weights.GetInfo(),
2690 biases);
2691 };
2692
2693 if(!IsDynamicTensor(outputInfo))
2694 {
2695 validateFunc(outputInfo, isSupported);
2696 }
2697 else
2698 {
2699 isSupported = AreDynamicTensorsSupported();
2700 }
2701
2702
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002703 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002704 {
2705 return false;
2706 }
2707
2708 armnn::IConnectableLayer* startLayer =
2709 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2710 if (!startLayer)
2711 {
2712 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2713 }
2714
Mike Kellyb5fdf382019-06-11 16:35:25 +01002715 input.Connect(startLayer->GetInputSlot(0));
2716
Kevin Mayfcf2a152020-09-08 16:06:32 +01002717 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2718 data, nullptr, validateFunc, activation);
arovir01b0717b52018-09-05 17:03:25 +01002719}
2720
Mike Kelly3c673942019-07-25 09:26:06 +01002721template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002722 typename HalOperation = typename HalPolicy::Operation,
2723 typename HalModel = typename HalPolicy::Model>
2724bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002725{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002726 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002727
2728 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2729 if (!input.IsValid())
2730 {
2731 return Fail("%s: Operation has invalid input", __func__);
2732 }
2733
Sadik Armagan98c0f662019-11-21 15:54:36 +00002734 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2735 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2736 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2737 {
2738 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2739 }
2740
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002741 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002742 if (!outputOperand)
2743 {
2744 return Fail("%s: Operation has invalid outputs", __func__);
2745 }
2746
2747 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002748
2749 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002750 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2751 {
2752 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2753 IsDequantizeSupported,
2754 data.m_Backends,
2755 isSupported,
2756 inputInfo,
2757 outputInfo);
2758 };
2759
2760 if(IsDynamicTensor(outputInfo))
2761 {
2762 isSupported = AreDynamicTensorsSupported();
2763 }
2764 else
2765 {
2766 validateFunc(outputInfo, isSupported);
2767 }
2768
Mike Kelly46272802019-08-14 17:00:48 +01002769 if (!isSupported)
2770 {
2771 return false;
2772 }
2773
2774 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
Mike Kellye2d611e2021-10-14 12:35:58 +01002775 if (!layer)
2776 {
2777 return Fail("%s: Could not add the DequantizeLayer", __func__);
2778 }
Mike Kelly46272802019-08-14 17:00:48 +01002779 input.Connect(layer->GetInputSlot(0));
2780
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002781 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002782}
2783
2784template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002785 typename HalOperation = typename HalPolicy::Operation,
2786 typename HalModel = typename HalPolicy::Model>
2787bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002788{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002789 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002790
2791 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2792 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2793
2794 if (!input0.IsValid() || !input1.IsValid())
2795 {
2796 return Fail("%s: Operation has invalid inputs", __func__);
2797 }
2798
2799 // The FuseActivation parameter is always the input index 2
2800 // and it should be optional
2801 ActivationFn activationFunction;
2802 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2803 {
2804 return Fail("%s: Operation has invalid inputs", __func__);
2805 }
2806
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002807 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002808 if (!output)
2809 {
2810 return Fail("%s: Could not read output 0", __func__);
2811 }
2812
2813 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002814
2815 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002816 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2817 {
2818 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2819 IsDivisionSupported,
2820 data.m_Backends,
2821 isSupported,
2822 input0.GetTensorInfo(),
2823 input1.GetTensorInfo(),
2824 outputInfo);
2825 };
2826
2827 if(!IsDynamicTensor(outputInfo))
2828 {
2829 validateFunc(outputInfo, isSupported);
2830 }
2831 else
2832 {
2833 isSupported = AreDynamicTensorsSupported();
2834 }
2835
Mike Kelly46272802019-08-14 17:00:48 +01002836 if (!isSupported)
2837 {
2838 return false;
2839 }
2840
2841 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
Mike Kelly46272802019-08-14 17:00:48 +01002842
Kevin Mayfcf2a152020-09-08 16:06:32 +01002843 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2844 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01002845 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01002846 return false;
Mike Kelly46272802019-08-14 17:00:48 +01002847 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01002848
2849 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
2850 data, nullptr, validateFunc, activationFunction);
2851
Mike Kelly46272802019-08-14 17:00:48 +01002852}
2853
2854template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002855 typename HalOperation = typename HalPolicy::Operation,
2856 typename HalModel = typename HalPolicy::Model>
2857bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002858{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002859 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002860
2861 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2862 if (!input.IsValid())
2863 {
2864 return Fail("%s: Operation has invalid inputs", __func__);
2865 }
2866
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002867 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002868 if (!outputOperand)
2869 {
2870 return Fail("%s: Operation has invalid outputs", __func__);
2871 }
2872
2873 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002874
2875 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002876 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2877 {
2878 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2879 IsFloorSupported,
2880 data.m_Backends,
2881 isSupported,
2882 input.GetTensorInfo(),
2883 outputInfo);
2884 };
2885
2886 if(!IsDynamicTensor(outputInfo))
2887 {
2888 validateFunc(outputInfo, isSupported);
2889 }
2890 else
2891 {
2892 isSupported = AreDynamicTensorsSupported();
2893 }
2894
Mike Kelly46272802019-08-14 17:00:48 +01002895 if (!isSupported)
2896 {
2897 return false;
2898 }
2899
2900 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
Mike Kellye2d611e2021-10-14 12:35:58 +01002901 if (!layer)
2902 {
2903 return Fail("%s: Could not add the FloorLayer", __func__);
2904 }
Mike Kelly46272802019-08-14 17:00:48 +01002905 input.Connect(layer->GetInputSlot(0));
2906
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002907 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002908}
2909
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002910inline bool IsQSymm8(const V1_0::Operand&)
2911{
2912 return false;
2913}
2914
Kevin May42477c12020-03-26 13:34:14 +00002915#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002916
2917inline bool IsQSymm8(const V1_2::Operand& operand)
2918{
2919 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2920}
2921
2922#endif
2923
Kevin May42477c12020-03-26 13:34:14 +00002924#ifdef ARMNN_ANDROID_NN_V1_3
2925
2926inline bool IsQSymm8(const V1_3::Operand& operand)
2927{
2928 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2929}
2930
2931#endif
2932
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002933enum class DequantizeStatus
2934{
2935 SUCCESS,
2936 NOT_REQUIRED,
2937 INVALID_OPERAND
2938};
2939
2940using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2941
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002942template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002943 typename HalOperation = typename HalPolicy::Operation,
2944 typename HalModel = typename HalPolicy::Model>
2945DequantizeResult DequantizeIfRequired(size_t operand_index,
2946 const HalOperation& operation,
2947 const HalModel& model,
2948 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002949{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002950 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002951
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002952 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002953 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002954 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002955 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002956 }
2957
2958 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2959 {
2960 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002961 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002962 }
2963
2964 const size_t weightsInputIndex = operation.inputs[operand_index];
2965
2966 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2967 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002968 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002969 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002970 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002971 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002972 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2973 {
2974 continue;
2975 }
2976
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002977 size_t outOpIndex = weightsInputIndex + 1;
2978 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002979 {
2980 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002981 }
2982
2983 if (outOpIndex != weightsInputIndex)
2984 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002985 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002986 }
2987
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002988 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Mike Kellye2d611e2021-10-14 12:35:58 +01002989
2990 if (!operand)
2991 {
2992 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
2993 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002994
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002995 if (!IsQSymm8(*operand))
2996 {
2997 // Only supporting dequantize from QSYMM8 to FLOAT
2998 break;
2999 }
3000
3001 // Allocate a new buffer for the dequantized data and manually dequantize
3002 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
3003 if (!startValue)
3004 {
3005 // Failed to get the operand address
3006 break;
3007 }
3008
3009 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
3010 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003011 const float quantizationScale = operand->scale;
3012
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003013 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
3014 for (size_t i = 0; i < dequantizedBufferLength; ++i)
3015 {
3016 float* dstPtr = dequantizedBuffer.get();
Mike Kellye2d611e2021-10-14 12:35:58 +01003017
3018 if (!dstPtr)
3019 {
3020 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
3021 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003022 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
3023 }
3024
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00003025 // Construct tensor info for dequantized ConstTensor
3026 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
3027 operand->dimensions.data(),
3028 armnn::DataType::Float32);
3029
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003030 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
3031 std::move(tensorInfo),
3032 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003033 }
3034
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003035 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003036}
3037
3038template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003039 typename HalOperation = typename HalPolicy::Operation,
3040 typename HalModel = typename HalPolicy::Model>
3041ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
3042 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003043 const ConversionData& data,
3044 size_t operandIndex,
3045 bool optional = false)
3046{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003047 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
3048
3049 DequantizeStatus status = std::get<3>(dequantized);
3050 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003051 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003052 case DequantizeStatus::INVALID_OPERAND:
3053 {
3054 // return invalid const tensor pin
3055 return ConstTensorPin();
3056 }
3057 case DequantizeStatus::NOT_REQUIRED:
3058 {
3059 return ConvertOperationInputToConstTensorPin<HalPolicy>(
3060 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
3061 }
3062 case DequantizeStatus::SUCCESS:
3063 default:
3064 {
3065 return ConstTensorPin(
3066 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
3067 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003068 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003069}
3070
3071
Mike Kelly46272802019-08-14 17:00:48 +01003072template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003073 typename HalOperation = typename HalPolicy::Operation,
3074 typename HalModel = typename HalPolicy::Model>
3075bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003076{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003077 using HalOperand = typename HalPolicy::Operand;
3078
Mike Kelly46272802019-08-14 17:00:48 +01003079 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3080 if (!input.IsValid())
3081 {
3082 return Fail("%s: Operation has invalid inputs", __func__);
3083 }
3084
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003085 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003086 if (!output)
3087 {
3088 return Fail("%s: Could not read output 0", __func__);
3089 }
3090
3091 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3092 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3093
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003094 LayerInputHandle weightsInput = LayerInputHandle();
3095 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3096 if (!weightsOperand)
Mike Kelly46272802019-08-14 17:00:48 +01003097 {
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003098 return Fail("%s: Could not read weights", __func__);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003099 }
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003100
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003101 // If weights are constant a separate constant layer will be created to store data.
3102 // Otherwise handle non const weights as inputs.
3103 weightsInput = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3104 if (!weightsInput.IsValid())
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003105 {
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003106 return Fail("%s: Operation has invalid inputs", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003107 }
3108
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003109 LayerInputHandle biasInput = LayerInputHandle();
3110 const HalOperand* biasOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3111 if (!biasOperand)
3112 {
3113 return Fail("%s: Could not read bias", __func__);
3114 }
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003115
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003116 // If bias are constant a separate constant layer will be created to store data.
3117 // Otherwise handle non const bias as inputs.
3118 biasInput = ConvertToLayerInputHandle<HalPolicy>(operation, 2, model, data); // 1D
3119 if (!biasInput.IsValid())
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003120 {
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003121 return Fail("%s: Operation has invalid inputs", __func__);
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003122 }
3123
Matthew Sloyan56c249c2021-08-09 12:49:23 +01003124 armnn::TensorInfo weightsInfo = weightsInput.GetTensorInfo();
Mike Kelly46272802019-08-14 17:00:48 +01003125 armnn::TensorInfo reshapedInfo = inputInfo;
Mike Kelly46272802019-08-14 17:00:48 +01003126 try
3127 {
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003128 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weightsInfo.GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01003129 }
3130 catch (const std::exception& e)
3131 {
Mike Kelly46272802019-08-14 17:00:48 +01003132 return Fail("%s: %s", __func__, e.what());
3133 }
3134
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003135 // Ensuring that the bias value is within 1% of the weights input (small float differences can exist)
Matthew Sloyan56c249c2021-08-09 12:49:23 +01003136 armnn::TensorInfo biasInfo = biasInput.GetTensorInfo();
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003137 SanitizeBiasQuantizationScale(biasInfo, weightsInfo, reshapedInfo);
Mike Kelly46272802019-08-14 17:00:48 +01003138
3139 ActivationFn activationFunction;
3140 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3141 {
3142 return Fail("%s: Operation has invalid inputs", __func__);
3143 }
3144
3145 armnn::FullyConnectedDescriptor desc;
3146 desc.m_TransposeWeightMatrix = true;
3147 desc.m_BiasEnabled = true;
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003148 desc.m_ConstantWeights = IsOperandConstant<HalPolicy>(*weightsOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003149
3150 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003151 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3152 {
Finn Williams49184462020-10-02 13:28:34 +01003153 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003154 weightsInfo.GetShape(),
Finn Williams49184462020-10-02 13:28:34 +01003155 outputInfo.GetShape(),
3156 desc.m_TransposeWeightMatrix))
3157 {
3158 isSupported = false;
3159 Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3160 return;
3161 }
3162
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003163 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003164 IsFullyConnectedSupported,
3165 data.m_Backends,
3166 isSupported,
3167 reshapedInfo,
3168 outputInfo,
3169 weightsInfo,
3170 biasInfo,
3171 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003172 };
3173
3174 if(!IsDynamicTensor(outputInfo))
3175 {
3176 validateFunc(outputInfo, isSupported);
3177 }
3178 else
3179 {
3180 isSupported = AreDynamicTensorsSupported();
3181 }
3182
Mike Kelly46272802019-08-14 17:00:48 +01003183 if (!isSupported)
3184 {
3185 return false;
3186 }
3187
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003188 // Add FullyConnected layer. Weights and bias will be connected as constant layers or non const inputs.
3189 armnn::IConnectableLayer* startLayer = data.m_Network->AddFullyConnectedLayer(desc);
Mike Kelly46272802019-08-14 17:00:48 +01003190
Kevin Mayfcf2a152020-09-08 16:06:32 +01003191 if (inputInfo.GetNumDimensions() > 2U)
Mike Kelly46272802019-08-14 17:00:48 +01003192 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003193 armnn::ReshapeDescriptor reshapeDescriptor;
3194 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
Mike Kelly46272802019-08-14 17:00:48 +01003195
Kevin Mayfcf2a152020-09-08 16:06:32 +01003196 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01003197 if (!reshapeLayer)
3198 {
3199 return Fail("%s: could not add the reshapeLayer", __func__);
3200 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003201 input.Connect(reshapeLayer->GetInputSlot(0));
3202 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3203 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003204 }
3205 else
3206 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003207 input.Connect(startLayer->GetInputSlot(0));
Mike Kelly46272802019-08-14 17:00:48 +01003208 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003209
Matthew Sloyan29cc9612021-07-16 10:21:12 +01003210 // Connect weights and bias inputs
3211 weightsInput.Connect(startLayer->GetInputSlot(1));
3212 biasInput.Connect(startLayer->GetInputSlot(2));
Sadik Armagan2e4a24a2021-03-18 13:59:40 +00003213
Kevin Mayfcf2a152020-09-08 16:06:32 +01003214 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3215 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003216}
3217
3218template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003219 typename HalOperation = typename HalPolicy::Operation,
3220 typename HalModel = typename HalPolicy::Model>
3221bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003222{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003223 using HalOperand = typename HalPolicy::Operand;
3224
Mike Kelly999e2092019-08-15 10:46:46 +01003225 if (operation.inputs.size() != 1)
3226 {
3227 return Fail("%s: Optional inputs are not supported", __func__);
3228 }
3229
Mike Kelly46272802019-08-14 17:00:48 +01003230 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3231 if (!input.IsValid())
3232 {
3233 return Fail("%s: Operation has invalid inputs", __func__);
3234 }
3235
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003236 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003237 if (!output)
3238 {
3239 return Fail("%s: Could not read output 0", __func__);
3240 }
3241
3242 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3243 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3244
Mike Kelly46272802019-08-14 17:00:48 +01003245 if (outputInfo.GetNumDimensions() != 4u)
3246 {
3247 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3248 }
3249
3250 armnn::L2NormalizationDescriptor desc;
3251 desc.m_DataLayout = armnn::DataLayout::NHWC;
3252
3253 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003254 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3255 {
3256 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3257 IsL2NormalizationSupported,
3258 data.m_Backends,
3259 isSupported,
3260 inputInfo,
3261 outputInfo,
3262 desc);
3263 };
3264
3265 if(!IsDynamicTensor(outputInfo))
3266 {
3267 validateFunc(outputInfo, isSupported);
3268 }
3269 else
3270 {
3271 isSupported = AreDynamicTensorsSupported();
3272 }
3273
Mike Kelly46272802019-08-14 17:00:48 +01003274 if (!isSupported)
3275 {
3276 return false;
3277 }
3278
3279 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
Mike Kellye2d611e2021-10-14 12:35:58 +01003280 if (!layer)
3281 {
3282 return Fail("%s: Could not add the L2NormalizationLayer", __func__);
3283 }
Mike Kelly46272802019-08-14 17:00:48 +01003284 input.Connect(layer->GetInputSlot(0));
3285
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003286 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003287}
3288
3289template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003290 typename HalOperation = typename HalPolicy::Operation,
3291 typename HalModel = typename HalPolicy::Model>
3292bool ConvertLocalResponseNormalization(const HalOperation& operation,
3293 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003294 ConversionData& data)
3295{
Mike Kelly999e2092019-08-15 10:46:46 +01003296 if (operation.inputs.size() != 5)
3297 {
3298 return Fail("%s: Optional inputs are not supported", __func__);
3299 }
3300
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003301 using HalOperand = typename HalPolicy::Operand;
3302 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003303
3304 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3305 if (!input.IsValid())
3306 {
3307 return Fail("%s: Operation has invalid inputs", __func__);
3308 }
3309
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003310 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003311 if (!output)
3312 {
3313 return Fail("%s: Could not read output 0", __func__);
3314 }
3315
3316 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3317 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3318
Mike Kelly46272802019-08-14 17:00:48 +01003319 if (outputInfo.GetNumDimensions() != 4u)
3320 {
3321 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3322 }
3323
3324 armnn::NormalizationDescriptor descriptor;
3325 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3326 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3327 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3328
3329 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003330 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003331 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3332 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3333 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3334 {
3335 return Fail("%s: Operation has invalid inputs", __func__);
3336 }
3337
3338 // ArmNN expects normSize to be the full size of the normalization
3339 // window rather than the radius as in AndroidNN.
3340 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3341
3342 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003343 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3344 {
3345 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3346 IsNormalizationSupported,
3347 data.m_Backends,
3348 isSupported,
3349 inputInfo,
3350 outputInfo,
3351 descriptor);
3352 };
3353
3354 if(!IsDynamicTensor(outputInfo))
3355 {
3356 validateFunc(outputInfo, isSupported);
3357 }
3358 else
3359 {
3360 isSupported = AreDynamicTensorsSupported();
3361 }
3362
Mike Kelly46272802019-08-14 17:00:48 +01003363 if (!isSupported)
3364 {
3365 return false;
3366 }
3367
Mike Kelly46272802019-08-14 17:00:48 +01003368 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01003369 if (!layer)
3370 {
3371 return Fail("%s: Could not add the NormalizationLayer", __func__);
3372 }
Mike Kelly46272802019-08-14 17:00:48 +01003373 input.Connect(layer->GetInputSlot(0));
3374
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003375 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003376}
3377
3378template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003379 typename HalOperation = typename HalPolicy::Operation,
3380 typename HalModel = typename HalPolicy::Model>
3381bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003382{
Mike Kelly46272802019-08-14 17:00:48 +01003383 armnn::ActivationDescriptor desc;
3384 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3385
3386 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3387}
3388
3389template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003390 typename HalOperation = typename HalPolicy::Operation,
3391 typename HalModel = typename HalPolicy::Model>
3392bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003393{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003394 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003395
3396 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3397 if (!input.IsValid())
3398 {
3399 return Fail("%s: Operation has invalid inputs", __func__);
3400 }
3401
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003402 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003403 if (!output)
3404 {
3405 return Fail("%s: Could not read output 0", __func__);
3406 }
3407
3408 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003409
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003410 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003411 if (!axisOperand)
3412 {
3413 return Fail("%s: Could not read input 1", __func__);
3414 }
3415
3416 std::vector<int32_t> axis;
3417 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3418 {
3419 return Fail("%s: Input 1 has invalid values", __func__);
3420 }
3421
3422 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3423
3424 // Convert the axis to unsigned int and remove duplicates.
3425 unsigned int rank = inputInfo.GetNumDimensions();
3426 std::set<unsigned int> uniqueAxis;
3427 std::transform(axis.begin(), axis.end(),
3428 std::inserter(uniqueAxis, uniqueAxis.begin()),
3429 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3430
3431 // Get the "keep dims" flag.
3432 int32_t keepDims = 0;
3433 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3434 {
3435 return Fail("%s: Could not read input 2", __func__);
3436 }
3437
3438 armnn::MeanDescriptor descriptor;
3439 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3440 descriptor.m_KeepDims = keepDims > 0;
3441
3442 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003443 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3444 {
3445 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3446 IsMeanSupported,
3447 data.m_Backends,
3448 isSupported,
3449 inputInfo,
3450 outputInfo,
3451 descriptor);
3452 };
3453
3454 if(!IsDynamicTensor(outputInfo))
3455 {
3456 validateFunc(outputInfo, isSupported);
3457 }
3458 else
3459 {
3460 isSupported = AreDynamicTensorsSupported();
3461 }
3462
Mike Kelly46272802019-08-14 17:00:48 +01003463 if (!isSupported)
3464 {
3465 return false;
3466 }
3467
3468 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01003469 if (!layer)
3470 {
3471 return Fail("%s: Could not add the MeanLayer", __func__);
3472 }
Mike Kelly46272802019-08-14 17:00:48 +01003473 input.Connect(layer->GetInputSlot(0));
3474
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003475 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003476}
3477
3478template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003479 typename HalOperation = typename HalPolicy::Operation,
3480 typename HalModel = typename HalPolicy::Model>
3481bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003482{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003483 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003484
3485 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3486 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3487
3488 if (!input0.IsValid() || !input1.IsValid())
3489 {
3490 return Fail("%s: Operation has invalid inputs", __func__);
3491 }
3492
3493 // The FuseActivation parameter is always the input index 2
3494 // and it should be optional
3495 ActivationFn activationFunction;
3496 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3497 {
3498 return Fail("%s: Operation has invalid inputs", __func__);
3499 }
3500
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003501 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003502
3503 if (outputOperand == nullptr)
3504 {
3505 return false;
3506 }
3507
3508 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +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 IsMultiplicationSupported,
3515 data.m_Backends,
3516 isSupported,
3517 input0.GetTensorInfo(),
3518 input1.GetTensorInfo(),
3519 outputInfo);
3520 };
3521
3522 if(!IsDynamicTensor(outputInfo))
3523 {
3524 validateFunc(outputInfo, isSupported);
3525 }
3526 else
3527 {
3528 isSupported = AreDynamicTensorsSupported();
3529 }
3530
Mike Kelly46272802019-08-14 17:00:48 +01003531 if (!isSupported)
3532 {
3533 return false;
3534 }
3535
3536 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
Mike Kelly46272802019-08-14 17:00:48 +01003537
Kevin Mayfcf2a152020-09-08 16:06:32 +01003538 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3539 if (!isReshapeSupported)
Mike Kelly46272802019-08-14 17:00:48 +01003540 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003541 return false;
3542 }
Sadik Armagan64b19b52019-08-19 09:49:58 +01003543
Kevin Mayfcf2a152020-09-08 16:06:32 +01003544 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3545 data, nullptr, validateFunc, activationFunction);
Mike Kelly46272802019-08-14 17:00:48 +01003546}
3547
3548template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003549 typename HalOperation = typename HalPolicy::Operation,
3550 typename HalModel = typename HalPolicy::Model>
3551bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003552{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003553 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003554
Mike Kelly3c673942019-07-25 09:26:06 +01003555 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3556 if (!input.IsValid())
3557 {
3558 return Fail("%s: Operation has invalid inputs", __func__);
3559 }
3560
3561 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3562 unsigned int rank = inputInfo.GetNumDimensions();
3563
3564 armnn::PadDescriptor descriptor;
3565 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3566 {
3567 return Fail("%s: Could not convert paddings", __func__);
3568 }
3569
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003570 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3571 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003572 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3573 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3574 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003575 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003576 {
3577 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3578 }
3579
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003580 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003581 if (!output)
3582 {
3583 return Fail("%s: Could not read output", __func__);
3584 }
3585
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003586 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003587
3588 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003589 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3590 {
3591 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3592 IsPadSupported,
3593 data.m_Backends,
3594 isSupported,
3595 inputInfo,
3596 outputInfo,
3597 descriptor);
3598 };
3599
3600 if(!IsDynamicTensor(outputInfo))
3601 {
3602 validateFunc(outputInfo, isSupported);
3603 }
3604 else
3605 {
3606 isSupported = AreDynamicTensorsSupported();
3607 }
3608
Mike Kelly3c673942019-07-25 09:26:06 +01003609 if (!isSupported)
3610 {
3611 return false;
3612 }
3613
3614 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01003615 if (!layer)
3616 {
3617 return Fail("%s: Could not add the PadLayer", __func__);
3618 }
Mike Kelly3c673942019-07-25 09:26:06 +01003619 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003620
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003621 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003622}
3623
Mike Kelly0a879362019-07-29 16:56:31 +01003624template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003625 typename HalOperation = typename HalPolicy::Operation,
3626 typename HalModel = typename HalPolicy::Model>
3627bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003628{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003629 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003630
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003631 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3632 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3633 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003634
3635 if (inputOperand == nullptr
3636 || requestedShapeOperand == nullptr
3637 || outputOperand == nullptr)
3638 {
3639 return Fail("%s: Operation has invalid inputs", __func__);
3640 }
3641
3642 if (requestedShapeOperand->dimensions.size() != 1)
3643 {
3644 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3645 __func__, requestedShapeOperand->dimensions.size());
3646 }
3647
3648 std::vector<int32_t> targetDimensions;
3649 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3650 {
3651 return Fail("%s: Could not read values of input 1", __func__);
3652 }
3653
3654 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3655
3656 Shape requestedShape;
3657 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3658 // function that resolves these values into a fully specified tensor shape.
3659 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3660 {
3661 return Fail("%s: Failed to resolve the requested shape", __func__);
3662 }
3663
Mike Kelly46272802019-08-14 17:00:48 +01003664 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3665 if (!input.IsValid())
3666 {
3667 return Fail("%s: Could not read input 0", __func__);
3668 }
3669
3670 armnn::ReshapeDescriptor reshapeDescriptor;
3671 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3672 requestedShape.dimensions.data());
3673
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003674 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3675
Mike Kelly46272802019-08-14 17:00:48 +01003676 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003677 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3678 {
3679 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3680 IsReshapeSupported,
3681 data.m_Backends,
3682 isSupported,
3683 input.GetTensorInfo(),
3684 outputInfo,
3685 reshapeDescriptor);
3686 };
3687
3688 if(!IsDynamicTensor(outputInfo))
3689 {
3690 validateFunc(outputInfo, isSupported);
3691 }
3692 else
3693 {
3694 isSupported = AreDynamicTensorsSupported();
3695 }
3696
Mike Kelly46272802019-08-14 17:00:48 +01003697 if (!isSupported)
3698 {
3699 return false;
3700 }
3701
3702 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01003703 if (!layer)
3704 {
3705 return Fail("%s: Could not add the ReshapeLayer", __func__);
3706 }
Mike Kelly46272802019-08-14 17:00:48 +01003707 input.Connect(layer->GetInputSlot(0));
3708
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003709 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003710}
3711
3712template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003713 typename HalOperation = typename HalPolicy::Operation,
3714 typename HalModel = typename HalPolicy::Model>
3715bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003716{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003717 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003718
Mike Kelly0a879362019-07-29 16:56:31 +01003719 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3720 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3721
3722 if (!input0.IsValid() || !input1.IsValid())
3723 {
3724 return Fail("%s: Operation has invalid inputs", __func__);
3725 }
3726
3727 // The FuseActivation parameter is always the input index 2
3728 // and it should be optional
3729 ActivationFn activationFunction;
3730 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3731 {
3732 return Fail("%s: Operation has invalid inputs", __func__);
3733 }
3734
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003735 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003736 if (!output)
3737 {
3738 return Fail("%s: Could not read output 0", __func__);
3739 }
3740
3741 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003742
3743 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003744 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3745 {
3746 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3747 IsSubtractionSupported,
3748 data.m_Backends,
3749 isSupported,
3750 input0.GetTensorInfo(),
3751 input1.GetTensorInfo(),
3752 outputInfo);
3753 };
3754
3755 if(IsDynamicTensor(outputInfo))
3756 {
3757 isSupported = AreDynamicTensorsSupported();
3758 }
3759 else
3760 {
3761 validateFunc(outputInfo, isSupported);
3762 }
3763
Mike Kelly0a879362019-07-29 16:56:31 +01003764 if (!isSupported)
3765 {
3766 return false;
3767 }
3768
3769 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
Mike Kelly0a879362019-07-29 16:56:31 +01003770
Kevin Mayfcf2a152020-09-08 16:06:32 +01003771 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3772 if (!isReshapeSupported)
Mike Kelly0a879362019-07-29 16:56:31 +01003773 {
Kevin Mayfcf2a152020-09-08 16:06:32 +01003774 return false;
Mike Kelly0a879362019-07-29 16:56:31 +01003775 }
Kevin Mayfcf2a152020-09-08 16:06:32 +01003776 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *startLayer, model,
3777 data, nullptr, validateFunc, activationFunction);
Mike Kelly0a879362019-07-29 16:56:31 +01003778}
3779
Finn Williams23b87b32019-07-30 11:44:05 +01003780template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003781 typename HalOperation = typename HalPolicy::Operation,
3782 typename HalModel = typename HalPolicy::Model>
3783bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003784{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003785 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003786
3787 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3788 if (!input.IsValid())
3789 {
3790 return Fail("%s: Operation has invalid inputs", __func__);
3791 }
3792
3793 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3794 unsigned int rank = inputInfo.GetNumDimensions();
3795 if (rank > 4)
3796 {
3797 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3798 }
3799
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003800 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003801 if (!output)
3802 {
3803 return Fail("%s: Could not read output 0", __func__);
3804 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003805
3806 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003807 {
3808 return Fail("%s: Dynamic output tensors are not supported", __func__);
3809 }
3810
3811 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3812 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003813 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003814
3815 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3816
3817 std::vector<int32_t> axis;
3818 if (!axisOperand)
3819 {
3820 axis.assign(dimensionSequence,
3821 dimensionSequence + rank);
3822 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003823 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003824 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003825 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003826 }
3827
3828 std::vector<uint32_t> outputDims;
3829 for (unsigned int i = 0; i < rank; i++)
3830 {
3831 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3832 auto currentDimension = inputInfo.GetShape()[i];
3833 if (skipSqueeze || currentDimension != 1)
3834 {
3835 outputDims.push_back(currentDimension);
3836 }
3837 }
3838
3839 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3840
3841 armnn::TensorInfo outputInfo = inputInfo;
3842 outputInfo.SetShape(outShape);
3843
3844 armnn::ReshapeDescriptor reshapeDesc;
3845 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3846
3847 bool isSupported = false;
3848 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3849 IsReshapeSupported,
3850 data.m_Backends,
3851 isSupported,
3852 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003853 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003854 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003855
Mike Kelly46272802019-08-14 17:00:48 +01003856 if (!isSupported)
3857 {
3858 return false;
3859 }
3860
3861 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
Mike Kellye2d611e2021-10-14 12:35:58 +01003862 if (!layer)
3863 {
3864 return Fail("%s: Could not add the ReshapeLayer", __func__);
3865 }
Mike Kelly46272802019-08-14 17:00:48 +01003866 input.Connect(layer->GetInputSlot(0));
3867
3868 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3869}
3870
3871template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003872 typename HalOperation = typename HalPolicy::Operation,
3873 typename HalModel = typename HalPolicy::Model>
3874bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003875{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003876 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003877
3878 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3879 if (!input.IsValid())
3880 {
3881 return Fail("%s: Operation has invalid inputs", __func__);
3882 }
3883
3884 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3885 unsigned int rank = inputInfo.GetNumDimensions();
3886 if (rank > 4)
3887 {
3888 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3889 }
3890
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003891 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003892 if (!output)
3893 {
3894 return Fail("%s: Could not read output 0", __func__);
3895 }
3896
3897 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003898
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003899 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3900 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3901 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003902
3903 std::vector<int32_t> beginValues;
3904 std::vector<int32_t> endValues;
3905 std::vector<int32_t> stridesValues;
3906
3907 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003908 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003909 {
3910 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3911 {
3912 return false;
3913 }
3914
3915 if (operandValues.size() != rank)
3916 {
3917 return false;
3918 }
3919
3920 return true;
3921 };
3922
3923 if (!ValidateInputOperands(*beginOperand, beginValues)
3924 || !ValidateInputOperands(*endOperand, endValues)
3925 || !ValidateInputOperands(*stridesOperand, stridesValues))
3926 {
3927 return Fail("%s: Operation has invalid input operand", __func__);
3928 }
3929
3930 // Stride cannot have value '0'
3931 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3932 {
3933 return Fail("%s: Stride must be non-zero value.", __func__);
3934 }
3935
3936 armnn::StridedSliceDescriptor descriptor;
3937 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3938 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3939 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3940 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3941
3942 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3943 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3944 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3945 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3946 {
3947 return Fail("%s: Operation has invalid inputs", __func__);
3948 }
3949
3950 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003951 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3952 {
3953 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3954 IsStridedSliceSupported,
3955 data.m_Backends,
3956 isSupported,
3957 inputInfo,
3958 outputInfo,
3959 descriptor);
3960 };
3961
3962 if(IsDynamicTensor(outputInfo))
3963 {
3964 isSupported = AreDynamicTensorsSupported();
3965 }
3966 else
3967 {
3968 validateFunc(outputInfo, isSupported);
3969 }
3970
Mike Kelly46272802019-08-14 17:00:48 +01003971 if (!isSupported)
3972 {
3973 return false;
3974 }
3975
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003976 // Check if slice can fit in a inferred output
3977 armnn::TensorShape inputShape = inputInfo.GetShape();
3978 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3979 {
3980 int stride = descriptor.m_Stride[i];
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003981
3982 if (descriptor.m_ShrinkAxisMask & (1 << i))
3983 {
3984 // If the difference between the start point and the end point of the slice on an axis being shrunk
3985 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3986 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3987 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3988 {
3989 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3990 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003991
3992 if(stride < 0)
3993 {
3994 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3995 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003996 }
3997 }
3998
Mike Kelly46272802019-08-14 17:00:48 +01003999 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01004000 if (!layer)
4001 {
4002 return Fail("%s: Could not add the StridedSliceLayer", __func__);
4003 }
Mike Kelly46272802019-08-14 17:00:48 +01004004 input.Connect(layer->GetInputSlot(0));
4005
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004006 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01004007}
4008
4009template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00004010 typename HalOperation = typename HalPolicy::Operation,
4011 typename HalModel = typename HalPolicy::Model>
4012bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01004013{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00004014 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01004015 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01004016
4017 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4018 if (!input.IsValid())
4019 {
4020 return Fail("%s: Operation has invalid inputs", __func__);
4021 }
4022
4023 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4024 unsigned int rank = inputInfo.GetNumDimensions();
4025 if (rank > 4)
4026 {
4027 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
4028 }
4029
4030 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
4031 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00004032 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01004033
4034 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01004035 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01004036 {
Mike Kelly46272802019-08-14 17:00:48 +01004037 for (unsigned int i = rank; i > 0; i--)
4038 {
Matthew Sloyan9b088d92020-09-14 15:12:55 +01004039 perm[rank - i] = armnn::numeric_cast<int> (i - 1);
Mike Kelly46272802019-08-14 17:00:48 +01004040 }
4041 }
Mike Kellyeec836e2020-02-18 10:03:30 +00004042 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01004043 {
Mike Kellyeec836e2020-02-18 10:03:30 +00004044 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01004045 }
4046
4047 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
4048
Mike Kelly4a956582020-02-28 10:32:09 +00004049 armnn::TransposeDescriptor transposeDesc;
4050 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01004051
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00004052 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01004053 if (!output)
4054 {
4055 return Fail("%s: Could not read output 0", __func__);
4056 }
4057
4058 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
4059
4060 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004061 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4062 {
4063 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4064 IsTransposeSupported,
4065 data.m_Backends,
4066 isSupported,
4067 inputInfo,
4068 outputInfo,
4069 transposeDesc);
4070 };
4071
4072 if(IsDynamicTensor(outputInfo))
4073 {
4074 isSupported = AreDynamicTensorsSupported();
4075 }
4076 else
4077 {
4078 validateFunc(outputInfo, isSupported);
4079 }
4080
Mike Kelly46272802019-08-14 17:00:48 +01004081 if (!isSupported)
4082 {
4083 return false;
4084 }
4085
Mike Kelly4a956582020-02-28 10:32:09 +00004086 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kellye2d611e2021-10-14 12:35:58 +01004087 if (!layer)
4088 {
4089 return Fail("%s: Could not add the TransposeLayer", __func__);
4090 }
Mike Kelly46272802019-08-14 17:00:48 +01004091 input.Connect(layer->GetInputSlot(0));
4092
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004093 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01004094}
4095
4096template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01004097 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01004098 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01004099 typename HalModel = typename HalPolicy::Model>
4100bool ConvertBatchToSpaceNd(const HalOperation& operation,
4101 const HalModel& model,
4102 ConversionData& data)
4103{
Finn Williams23b87b32019-07-30 11:44:05 +01004104
4105 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4106 if (!input.IsValid())
4107 {
4108 return Fail("%s: Operation has invalid inputs", __func__);
4109 }
4110
4111 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4112 if (!output)
4113 {
4114 return Fail("%s: Could not read output 0", __func__);
4115 }
4116
4117 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01004118
4119 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4120 if (!blockOperand)
4121 {
4122 return Fail("%s: Could not read input 1", __func__);
4123 }
4124
4125 // Convert the block operand to int32
4126 std::vector<int32_t> block;
4127 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
4128 {
4129 return Fail("%s: Input 1 has invalid values", __func__);
4130 }
4131
4132 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4133
4134 unsigned int rank = inputInfo.GetNumDimensions();
4135 if (rank != 4)
4136 {
4137 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
4138 }
4139
4140 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4141 {
4142 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4143 " greater than or equal to 1", __func__);
4144 }
4145
4146 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4147 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4148 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4149
Kevin May42477c12020-03-26 13:34:14 +00004150 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004151 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004152 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004153 }
4154 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4155 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4156
4157 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004158 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4159 {
4160 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4161 IsBatchToSpaceNdSupported,
4162 data.m_Backends,
4163 isSupported,
4164 inputInfo,
4165 outputInfo,
4166 batchToSpaceNdDesc);
4167 };
4168
4169 if(!IsDynamicTensor(outputInfo))
4170 {
4171 validateFunc(outputInfo, isSupported);
4172 }
4173 else
4174 {
4175 isSupported = AreDynamicTensorsSupported();
4176 }
4177
4178
Finn Williams23b87b32019-07-30 11:44:05 +01004179 if (!isSupported)
4180 {
4181 return false;
4182 }
4183
4184 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
Mike Kellye2d611e2021-10-14 12:35:58 +01004185 if (!layer)
4186 {
4187 return Fail("%s: Could not add the BatchToSpaceNdLayer", __func__);
4188 }
Finn Williams23b87b32019-07-30 11:44:05 +01004189 input.Connect(layer->GetInputSlot(0));
4190
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004191 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004192}
Mike Kelly0a879362019-07-29 16:56:31 +01004193
Finn Williamsd74c5052019-07-30 17:06:00 +01004194template<typename HalPolicy,
4195 typename HalOperation = typename HalPolicy::Operation,
4196 typename HalOperand = typename HalPolicy::Operand,
4197 typename HalModel = typename HalPolicy::Model>
4198bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4199{
4200 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4201 if (!input.IsValid())
4202 {
4203 return Fail("%s: Operation has invalid inputs", __func__);
4204 }
4205
4206 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4207 unsigned int rank = inputInfo.GetNumDimensions();
4208 unsigned int spatialDim = rank - 2;
4209
4210 if (rank != 4)
4211 {
4212 Fail("%s: Only inputs with rank 4 are supported", __func__);
4213 }
4214
4215 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4216 if (!output)
4217 {
4218 return Fail("%s: Could not read output 0", __func__);
4219 }
4220
4221 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004222
4223 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4224 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4225
4226 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4227 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4228 {
4229 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4230 }
4231
4232 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004233 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4234 {
4235 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4236 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004237 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4238 {
4239 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4240 }
4241
4242 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4243 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4244 {
4245 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4246 }
4247
4248 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4249 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004250 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4251 {
4252 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4253 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004254 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4255 {
4256 int paddingBeforeInput = paddings[i];
4257 int paddingAfterInput = paddings[i + 1];
4258 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4259 {
4260 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4261 }
4262
4263 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4264 }
4265
4266 armnn::SpaceToBatchNdDescriptor descriptor;
4267 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4268 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4269 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4270
Kevin May42477c12020-03-26 13:34:14 +00004271 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004272 {
4273 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4274 }
4275
4276 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004277 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4278 {
4279 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4280 IsSpaceToBatchNdSupported,
4281 data.m_Backends,
4282 isSupported,
4283 inputInfo,
4284 outputInfo,
4285 descriptor);
4286 };
4287
4288 if(IsDynamicTensor(outputInfo))
4289 {
4290 isSupported = AreDynamicTensorsSupported();
4291 }
4292 else
4293 {
4294 validateFunc(outputInfo, isSupported);
4295 }
4296
Finn Williamsd74c5052019-07-30 17:06:00 +01004297 if (!isSupported)
4298 {
4299 return false;
4300 }
4301
4302 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
Mike Kellye2d611e2021-10-14 12:35:58 +01004303 if (!layer)
4304 {
4305 return Fail("%s: Could not add the BatchToSpaceLayer", __func__);
4306 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004307 input.Connect(layer->GetInputSlot(0));
4308
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004309 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004310}
4311
saoste01b8471482018-10-10 09:44:51 +01004312} // namespace armnn_driver