blob: fabf18967eaead195727b2c23dcf494bd24cab3a [file] [log] [blame]
arovir01b0717b52018-09-05 17:03:25 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01008#include "Utils.hpp"
9
arovir01b0717b52018-09-05 17:03:25 +010010#include <armnn/ArmNN.hpp>
Ferran Balaguerd30093c2019-07-09 17:04:47 +010011#include <armnn/ILayerSupport.hpp>
12#include <armnn/BackendHelper.hpp>
arovir01b0717b52018-09-05 17:03:25 +010013
Mike Kellyb5fdf382019-06-11 16:35:25 +010014#include "armnn/src/armnnUtils/DataLayoutIndexed.hpp"
arovir01b0717b52018-09-05 17:03:25 +010015#include "armnn/src/armnnUtils/Permute.hpp"
arovir01b0717b52018-09-05 17:03:25 +010016
Mike Kelly46272802019-08-14 17:00:48 +010017#include "1.0/FullyConnected.hpp"
18
arovir01b0717b52018-09-05 17:03:25 +010019#include <ActivationFunctor.h>
20#include <CpuExecutor.h>
21#include <OperationsUtils.h>
22
23#include <boost/assert.hpp>
24#include <boost/core/ignore_unused.hpp>
Aron Virginas-Tar0e7ab542019-04-10 15:02:31 +010025#include <boost/numeric/conversion/cast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010026#include <boost/test/tools/floating_point_comparison.hpp>
27
28#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010029#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010030
31namespace armnn_driver
32{
33
34///
35/// Helper classes
36///
37
38struct ConversionData
39{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010040 ConversionData(const std::vector<armnn::BackendId>& backends)
41 : m_Backends(backends)
42 , m_Network(nullptr, nullptr)
arovir01b0717b52018-09-05 17:03:25 +010043 {}
44
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010045 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010046 armnn::INetworkPtr m_Network;
47 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
48 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
49};
50
51class LayerInputHandle
52{
53public:
54 LayerInputHandle();
55 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
56
57 bool IsValid() const;
58
59 void Connect(armnn::IInputSlot& inputSlot);
60
61 const armnn::TensorInfo& GetTensorInfo() const;
62
63private:
64 armnn::IOutputSlot* m_OutputSlot;
65 bool m_Valid;
66 armnn::TensorInfo m_TensorInfo;
67};
68
69class ConstTensorPin
70{
71public:
72 // Creates an invalid tensor pin (can be used to signal errors)
73 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
74 ConstTensorPin(bool optional = false);
75
76 // @param tensorInfo TensorInfo associated with the tensor.
77 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
78 // the model being converted.
79 // @param numBytes Number of bytes for the tensor data.
80 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
81 const armnn::PermutationVector& mappings);
82
83 ConstTensorPin(const ConstTensorPin& other) = delete;
84 ConstTensorPin(ConstTensorPin&& other) = default;
85
86 bool IsValid() const;
87 bool IsOptional() const;
88
89 const armnn::ConstTensor& GetConstTensor() const;
90 const armnn::ConstTensor* GetConstTensorPtr() const;
91
92private:
93 armnn::ConstTensor m_ConstTensor;
94
95 // Owned memory for swizzled tensor data, only required if the tensor needed
96 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
97 // the pools associated with the model being converted.
98 std::vector<uint8_t> m_SwizzledTensorData;
99
100 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
101 bool m_Optional;
102};
103
104} // namespace armnn_driver
105
106///
107/// Utility functions
108///
109
110namespace
111{
112
113using namespace armnn_driver;
114using namespace android::nn;
115
116// Convenience function to log the reason for failing to convert a model.
117// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
118template<class... Args>
119static bool Fail(const char* formatStr, Args&&... args)
120{
121 ALOGD(formatStr, std::forward<Args>(args)...);
122 return false;
123}
124
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100125// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
126// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
127#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100128try \
129{ \
130 for (auto&& backendId : backends) \
131 { \
132 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
133 if (layerSupportObject) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100134 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100135 std::string reasonIfUnsupported; \
136 supported = \
137 layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
138 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100139 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100140 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100141 } \
142 else \
143 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100144 if (reasonIfUnsupported.size() > 0) \
145 { \
146 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
147 } \
148 else \
149 { \
150 ALOGD("%s: not supported by armnn", funcName); \
151 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100152 } \
153 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100154 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100155 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100156 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100157 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100158 } \
159 if (!supported) \
160 { \
161 ALOGD("%s: not supported by any specified backend", funcName); \
162 } \
163} \
164catch (const armnn::InvalidArgumentException &e) \
165{ \
166 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
167}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100168
Mike Kellyb5fdf382019-06-11 16:35:25 +0100169template<typename Operand>
170armnn::TensorShape GetTensorShapeForOperand(const Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100171{
172 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
173}
174
Matthew Bentham912b3622019-05-03 15:49:14 +0100175inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100176{
Matthew Bentham912b3622019-05-03 15:49:14 +0100177 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
178 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
179 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100180}
181
Mike Kellyb5fdf382019-06-11 16:35:25 +0100182#ifdef ARMNN_ANDROID_NN_V1_2
183
184inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
185{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000186 return type == V1_2::OperandType::BOOL ||
187 type == V1_2::OperandType::TENSOR_FLOAT16 ||
188 type == V1_2::OperandType::TENSOR_FLOAT32 ||
189 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
190 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
191 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100192 type == V1_2::OperandType::TENSOR_INT32;
193}
194
195#endif
196
197inline bool IsBool(V1_0::Operand)
198{
199 return false;
200}
201
Sadik Armagan61113162019-07-25 09:09:40 +0100202inline bool Is12Operand(V1_0::Operand)
203{
204 return false;
205}
206
Mike Kellyb5fdf382019-06-11 16:35:25 +0100207#ifdef ARMNN_ANDROID_NN_V1_2
208
209inline bool IsBool(V1_2::Operand operand)
210{
211 return operand.type == V1_2::OperandType::BOOL;
212}
213
Sadik Armagan61113162019-07-25 09:09:40 +0100214/// Checks if a operand is 1_2 Operand
215inline bool Is12Operand(V1_2::Operand)
216{
217 return true;
218}
219
Mike Kellyb5fdf382019-06-11 16:35:25 +0100220#endif
221
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100222template<typename LayerHandleType>
223armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network, LayerHandleType& inputLayer,
224 armnn::TensorInfo reshapeInfo)
225{
226 armnn::ReshapeDescriptor reshapeDescriptor;
227 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
228
229 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
230 BOOST_ASSERT(reshapeLayer != nullptr);
231
232 // Attach the input layer to the reshape layer
233 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
234 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
235
236 return *reshapeLayer;
237}
238
Sadik Armagan64b19b52019-08-19 09:49:58 +0100239bool BroadcastTensor(LayerInputHandle& input0, LayerInputHandle& input1,
240 armnn::IConnectableLayer* startLayer, ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100241{
242 BOOST_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100243
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100244 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
245 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
246
247 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
248 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
249
250 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100251 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100252 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
253 input0.Connect(startLayer->GetInputSlot(0));
254 input1.Connect(startLayer->GetInputSlot(1));
255
Sadik Armagan64b19b52019-08-19 09:49:58 +0100256 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100257 }
258
259 // Since the number of dimensions do not match then we need to add degenerate dimensions
260 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
261
262 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
263 unsigned int sizeDifference = std::abs(boost::numeric_cast<int>(inputDimensions0) -
264 boost::numeric_cast<int>(inputDimensions1));
265
266 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
267 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
268 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
269
270 const armnn::TensorShape& smallShape = smallInfo.GetShape();
271 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
272 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
273 {
274 reshapedDimensions[i] = smallShape[i - sizeDifference];
275 }
276
277 armnn::TensorInfo reshapedInfo = smallInfo;
278 reshapedInfo.SetShape(armnn::TensorShape{ boost::numeric_cast<unsigned int>(reshapedDimensions.size()),
279 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100280
281 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
282 armnn::ReshapeDescriptor reshapeDescriptor;
283
284 bool isSupported = false;
285 FORWARD_LAYER_SUPPORT_FUNC(__func__,
286 IsReshapeSupported,
287 data.m_Backends,
288 isSupported,
289 reshapedInfo,
290 reshapeDescriptor);
291 if (!isSupported)
292 {
293 return false;
294 }
295
296 BOOST_ASSERT(data.m_Network != nullptr);
297 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100298
299 if (input0IsSmaller)
300 {
301 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
302 //
303 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100304 // | |
305 // Reshape |
306 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100307 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100308
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100309 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
310 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100311 }
312 else
313 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100314 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
315 //
316 // Input0 Input1
317 // | |
318 // | Reshape
319 // \ /
320 // StartLayer
321
arovir01b0717b52018-09-05 17:03:25 +0100322 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100323 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100324 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100325
326 return true;
arovir01b0717b52018-09-05 17:03:25 +0100327}
328
329void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
330 android::nn::PaddingScheme scheme)
331{
332 int32_t padHead;
333 int32_t padTail;
334 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
335 outPadHead = boost::numeric_cast<uint32_t>(padHead);
336 outPadTail = boost::numeric_cast<uint32_t>(padTail);
337}
338
Mike Kelly86b36d42019-07-12 16:39:33 +0100339#ifdef ARMNN_ANDROID_NN_V1_2
340
341void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
342 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
343{
344 int32_t padHead;
345 int32_t padTail;
346 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
347 outPadHead = boost::numeric_cast<uint32_t>(padHead);
348 outPadTail = boost::numeric_cast<uint32_t>(padTail);
349}
350
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100351void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, uint32_t stride, int32_t& outPadHead,
352 int32_t& outPadTail, android::nn::PaddingScheme scheme)
353{
354 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
355}
356
Mike Kelly86b36d42019-07-12 16:39:33 +0100357#endif
358
Matthew Bentham912b3622019-05-03 15:49:14 +0100359Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100360{
361 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100362 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100363 shape.dimensions = operand.dimensions;
364 shape.scale = operand.scale;
365 shape.offset = operand.zeroPoint;
366 return shape;
367}
368
Mike Kelly46272802019-08-14 17:00:48 +0100369#ifdef ARMNN_ANDROID_NN_V1_2
370
371Shape GetOperandShape(const V1_2::Operand& operand)
372{
373 Shape shape;
374 shape.type = OperandType(operand.type);
375 shape.dimensions = operand.dimensions;
376 shape.scale = operand.scale;
377 shape.offset = operand.zeroPoint;
378 return shape;
379}
380
381#endif
382
arovir01b0717b52018-09-05 17:03:25 +0100383// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
384// 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 +0100385// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
386// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100387void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000388 const armnn::TensorInfo& weightInfo,
389 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100390{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000391 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100392 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000393 // NOTE: Bias scale is always set to 0 for per-axis quantization and
394 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
395 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100396 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000397 return biasScale * inputInfo.GetQuantizationScale();
398 };
399
400 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
401 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
402
403 biasInfo.SetQuantizationScales(biasScales);
404 biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
405
406 ALOGV("Bias quantization params have been updated for per-axis quantization");
407 }
408 else
409 {
410 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
411 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
412 {
413 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
414 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
415 {
416 ALOGW("Bias quantization scale has been modified to match input * weights");
417 biasInfo.SetQuantizationScale(expectedBiasScale);
418 }
arovir01b0717b52018-09-05 17:03:25 +0100419 }
420 }
421}
422
423// 4D Tensor Permutations
424const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
425const armnn::PermutationVector NHWCToArmNN({ 0U, 2U, 3U, 1U });
426const armnn::PermutationVector ArmNNToNHWC({ 0U, 3U, 1U, 2U });
427const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
428
429// 3D Permutation Vectors
430const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
431const armnn::PermutationVector RotateTensorLeft({ 2U, 0U, 1U });
432const armnn::PermutationVector RotateTensorRight({ 1U, 2U, 0U });
433
434template<typename OSlot>
435armnn::IConnectableLayer& AddPermuteLayer(armnn::INetwork& network, OSlot& input,
436 const armnn::PermutationVector& mappings)
437{
438 // Add swizzle layer
439 armnn::IConnectableLayer* const layer = network.AddPermuteLayer(mappings);
440
441 BOOST_ASSERT(layer != nullptr);
442
443 // Connect input to swizzle layer
444 input.Connect(layer->GetInputSlot(0));
445
446 // Setup swizzled output
447 const armnn::TensorInfo outInfo = armnnUtils::Permuted(input.GetTensorInfo(), mappings);
448 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
449
450 return *layer;
451}
452
453void SwizzleIn(armnn::INetwork& network, LayerInputHandle& input, armnn::IConnectableLayer& layer, unsigned int index)
454{
455 // Add swizzle layer
456 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, input, NHWCToArmNN);
457 // Connect swizzled input to layer
458 swizzleLayer.GetOutputSlot(0).Connect(layer.GetInputSlot(index));
459}
460
461armnn::IConnectableLayer& DeswizzleOut(armnn::INetwork& network, armnn::IConnectableLayer& layer, unsigned int index)
462{
463 // Add deswizzle layer
464 armnn::IConnectableLayer& deswizzleLayer = AddPermuteLayer(network, layer.GetOutputSlot(index), ArmNNToNHWC);
465 return deswizzleLayer;
466}
467
468// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
469armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network,
470 LayerInputHandle& input,
471 armnn::IConnectableLayer& firstLayer,
472 armnn::IConnectableLayer& lastLayer)
473{
474 SwizzleIn(network, input, firstLayer, 0);
475 return DeswizzleOut(network, lastLayer, 0);
476}
477
478// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
479armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network, LayerInputHandle& input,
480 armnn::IConnectableLayer& layer)
481{
482 return SwizzleInDeswizzleOut(network, input, layer, layer);
483}
484
485bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
486 const armnn::TensorShape & outputShape,
487 uint32_t concatDim)
488{
489 // Validate the output shape is correct given the input shapes (which have just been validated)
490 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
491 if (outputShape.GetNumDimensions() != numDimensions)
492 {
493 return Fail("%s: Output shape has wrong number of dimensions", __func__);
494 }
495
496 unsigned int outputSizeAlongConcatenatedDimension = 0;
497 for (unsigned int i = 0; i < inputShapes.size(); i++)
498 {
499 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
500 }
501
502 for (unsigned int i = 0; i < numDimensions; ++i)
503 {
504 if (i == concatDim)
505 {
506 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
507 {
508 return Fail(
509 "%s: Invalid output shape for dimension %d (%d != %d)",
510 __func__,
511 i,
512 outputShape[i],
513 outputSizeAlongConcatenatedDimension);
514 }
515 }
516 else
517 {
518 if (outputShape[i] != inputShapes[0][i])
519 {
520 return Fail("%s: Invalid output shape", __func__);
521 }
522 }
523 }
524
525 return true;
526}
527
528bool RequiresReshape(armnn::TensorShape & inputShape)
529{
530 return inputShape.GetNumDimensions() < 3;
531}
532
arovir01b0717b52018-09-05 17:03:25 +0100533void SwizzleInputs(armnn::INetwork& network,
534 std::vector<LayerInputHandle>& inputs,
535 std::vector<armnn::TensorShape>& inputShapes,
536 const armnn::PermutationVector& mapping)
537{
538 if (!mapping.IsEqual(IdentityPermutation4D))
539 {
540 size_t nInputs = inputs.size();
541 for (size_t i=0; i<nInputs; ++i)
542 {
543 // add swizzle layer
544 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, inputs[i], mapping);
545 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
546 auto& outputInfo = outputSlot.GetTensorInfo();
547 // replace inputs with the swizzled ones
548 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
549 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
550 }
551 }
552}
553
narpra01f176d5a2018-11-18 20:17:48 +0000554bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
555 int32_t & concatDimension,
556 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100557{
narpra01f176d5a2018-11-18 20:17:48 +0000558 bool needPermute = false;
arovir01b0717b52018-09-05 17:03:25 +0100559 BOOST_ASSERT(numberOfDimensions >= 3);
560
561 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000562 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
563 // or along dimension 0 or 2 for a 3-D tensor.
564 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100565 {
narpra01f176d5a2018-11-18 20:17:48 +0000566 concatDimension = 1;
567 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
568 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100569 }
narpra01f176d5a2018-11-18 20:17:48 +0000570 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100571 {
narpra01f176d5a2018-11-18 20:17:48 +0000572 concatDimension = 0;
573 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
574 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100575 }
narpra01f176d5a2018-11-18 20:17:48 +0000576 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100577}
578
579} // anonymous namespace
580
581namespace armnn_driver
582{
583
584//// Creates an ArmNN activation layer and connects it to the given layer, if the
585//// passed in AndroidNN activation function requires so.
586//// @return The end layer of the sequence of layers built for the given AndroidNN
587//// activation function or nullptr if an error occurred (e.g. unsupported activation).
588//// Note that the end layer matches the input layer if no activation is required
589//// (the sequence of layers has length 1).
590armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
591 ActivationFn activation,
592 armnn::IConnectableLayer* prevLayer,
593 ConversionData& data);
594
595} // namespace armnn_driver
596
597///
598/// Utility templates
599///
600
601namespace armnn_driver
602{
603
604using namespace android::nn;
605
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100606template<typename HalPolicy,
607 typename HalOperand = typename HalPolicy::Operand,
608 typename HalOperation = typename HalPolicy::Operation,
609 typename HalModel = typename HalPolicy::Model>
610const HalOperand* GetInputOperand(const HalOperation& operation,
611 uint32_t inputIndex,
612 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100613 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100614{
615 if (inputIndex >= operation.inputs.size())
616 {
saoste01b8471482018-10-10 09:44:51 +0100617 if (failOnIndexOutOfBounds)
618 {
619 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
620 }
arovir01b0717b52018-09-05 17:03:25 +0100621 return nullptr;
622 }
623
624 BOOST_ASSERT(operation.inputs[inputIndex] < model.operands.size()); // Model should have been validated beforehand
625 return &model.operands[operation.inputs[inputIndex]];
626}
627
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100628template<typename HalPolicy,
629 typename HalOperand = typename HalPolicy::Operand,
630 typename HalOperation = typename HalPolicy::Operation,
631 typename HalModel = typename HalPolicy::Model>
632const HalOperand* GetOutputOperand(const HalOperation& operation,
633 uint32_t outputIndex,
634 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100635{
636 if (outputIndex >= operation.outputs.size())
637 {
638 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
639 return nullptr;
640 }
641
642 // Model should have been validated beforehand
643 BOOST_ASSERT(operation.outputs[outputIndex] < model.operands.size());
644
645 return &model.operands[operation.outputs[outputIndex]];
646}
647
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100648template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100649 typename HalOperand = typename HalPolicy::Operand,
650 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100651const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100652 const HalModel& model,
653 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000654 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100655{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100656 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100657
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100658 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100659 switch (operand.lifetime)
660 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100661 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100662 {
663 // Constant found in model.operandValues
664 valueStart = &model.operandValues[operand.location.offset];
665 break;
666 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100667 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100668 {
669 // Constant specified via a Memory object
670 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
671 break;
672 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100673 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000674 {
675 // An optional input tensor with no values is not an error so should not register as a fail
676 if (optional)
677 {
678 valueStart = nullptr;
679 break;
680 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100681 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000682 }
arovir01b0717b52018-09-05 17:03:25 +0100683 default:
684 {
685 // Unsupported/invalid (e.g. can't get value of an input to the model)
686 Fail("%s: unsupported/invalid operand lifetime: %s",
687 __func__, toString(operand.lifetime).c_str());
688 valueStart = nullptr;
689 }
690 }
691
692 return valueStart;
693}
694
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100695template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100696 typename HalOperation = typename HalPolicy::Operation,
697 typename HalModel = typename HalPolicy::Model,
698 typename HalOperandType = typename HalPolicy::OperandType>
699bool GetOperandType(const HalOperation& operation,
700 uint32_t inputIndex,
701 const HalModel& model,
702 HalOperandType& type)
703{
704 using HalOperand = typename HalPolicy::Operand;
705
706 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
707 if (!operand)
708 {
709 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
710 }
711
712 type = operand->type;
713 return true;
714}
715
716template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000717 typename HalOperand = typename HalPolicy::Operand>
718bool IsOperandConstant(const HalOperand& operand)
719{
720 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
721
722 HalOperandLifeTime lifetime = operand.lifetime;
723
724 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
725 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
726 lifetime == HalOperandLifeTime::NO_VALUE;
727}
728
729template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100730 typename HalOperand = typename HalPolicy::Operand,
731 typename HalModel = typename HalPolicy::Model>
732ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
733 const HalModel& model,
734 const ConversionData& data,
735 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
736 const armnn::TensorShape* overrideTensorShape = nullptr,
737 bool optional = false)
738{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100739 if (!IsOperandTypeSupportedForTensors(operand.type))
740 {
741 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
742 return ConstTensorPin();
743 }
744
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000745 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100746 {
747 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
748 return ConstTensorPin();
749 }
750
751 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
752 if (!valueStart)
753 {
754 if (optional)
755 {
756 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
757 return ConstTensorPin(true);
758 }
759 // mandatory tensor with no values
760 Fail("%s: failed to get operand address", __func__);
761 return ConstTensorPin();
762 }
763
764 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000765 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
766 if (tensorInfo.HasPerAxisQuantization())
767 {
768 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
769 }
770
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100771 if (overrideTensorShape != nullptr)
772 {
773 tensorInfo.SetShape(*overrideTensorShape);
774 }
775 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
776}
777
778template<typename HalPolicy,
779 typename HalOperation = typename HalPolicy::Operation,
780 typename HalModel = typename HalPolicy::Model>
781ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
782 uint32_t inputIndex,
783 const HalModel& model,
784 const ConversionData& data,
785 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
786 const armnn::TensorShape* overrideTensorShape = nullptr,
787 bool optional = false)
788{
789 using HalOperand = typename HalPolicy::Operand;
790
791 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
792 if (!operand)
793 {
794 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
795 return ConstTensorPin();
796 }
797 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
798 model,
799 data,
800 dimensionMappings,
801 overrideTensorShape,
802 optional);
803}
804
805template<typename HalPolicy,
806 typename OutputType,
807 typename HalOperandType = typename HalPolicy::OperandType,
808 typename HalOperation = typename HalPolicy::Operation,
809 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100810bool GetInputScalar(const HalOperation& operation,
811 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100812 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100813 OutputType& outValue,
814 const HalModel& model,
815 const ConversionData& data)
816{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100817 using HalOperand = typename HalPolicy::Operand;
818
819 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +0100820 if (!operand)
821 {
822 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
823 }
824
825 if (operand->type != type)
826 {
827 return Fail("%s: unexpected operand type: %s (should be %s)",
828 __func__, toString(operand->type).c_str(), toString(type).c_str());
829 }
830
831 if (operand->location.length != sizeof(OutputType))
832 {
833 return Fail("%s: incorrect operand location length: %i (should be %i)",
834 __func__, operand->location.length, sizeof(OutputType));
835 }
836
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100837 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100838 if (!valueAddress)
839 {
840 return Fail("%s: failed to get address for operand", __func__);
841 }
842
843 outValue = *(static_cast<const OutputType*>(valueAddress));
844 return true;
845}
846
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100847template<typename HalPolicy,
848 typename HalOperation = typename HalPolicy::Operation,
849 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100850bool GetInputInt32(const HalOperation& operation,
851 uint32_t inputIndex,
852 int32_t& outValue,
853 const HalModel& model,
854 const ConversionData& data)
855{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100856 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100857}
858
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100859template<typename HalPolicy,
860 typename HalOperation = typename HalPolicy::Operation,
861 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100862bool GetInputFloat32(const HalOperation& operation,
863 uint32_t inputIndex,
864 float& outValue,
865 const HalModel& model,
866 const ConversionData& data)
867{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100868 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100869}
870
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100871template<typename HalPolicy,
872 typename HalOperation = typename HalPolicy::Operation,
873 typename HalOperandType = typename HalPolicy::OperandType,
874 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100875bool GetInputActivationFunctionImpl(const HalOperation& operation,
876 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100877 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100878 ActivationFn& outActivationFunction,
879 const HalModel& model,
880 const ConversionData& data)
881{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100882 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100883 {
884 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
885 __func__,
886 toString(type).c_str(),
887 toString(OperandType::INT32).c_str(),
888 toString(OperandType::TENSOR_INT32).c_str());
889 }
890
891 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100892 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100893 {
894 return Fail("%s: failed to get activation input value", __func__);
895 }
896 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
897 return true;
898}
899
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100900template<typename HalPolicy,
901 typename HalOperation = typename HalPolicy::Operation,
902 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100903bool GetInputActivationFunction(const HalOperation& operation,
904 uint32_t inputIndex,
905 ActivationFn& outActivationFunction,
906 const HalModel& model,
907 const ConversionData& data)
908{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100909 return GetInputActivationFunctionImpl<HalPolicy>(operation,
910 inputIndex,
911 HalPolicy::OperandType::INT32,
912 outActivationFunction,
913 model,
914 data);
arovir01b0717b52018-09-05 17:03:25 +0100915}
916
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100917template<typename HalPolicy,
918 typename HalOperation = typename HalPolicy::Operation,
919 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100920bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
921 uint32_t inputIndex,
922 ActivationFn& outActivationFunction,
923 const HalModel& model,
924 const ConversionData& data)
925{
926 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100927 return GetInputActivationFunctionImpl<HalPolicy>(operation,
928 inputIndex,
929 HalPolicy::OperandType::INT32,
930 outActivationFunction,
931 model,
932 data);
arovir01b0717b52018-09-05 17:03:25 +0100933}
934
935
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100936template<typename HalPolicy,
937 typename HalOperation = typename HalPolicy::Operation,
938 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100939bool GetOptionalInputActivation(const HalOperation& operation,
940 uint32_t inputIndex,
941 ActivationFn& activationFunction,
942 const HalModel& model,
943 const ConversionData& data)
944{
945 if (operation.inputs.size() <= inputIndex)
946 {
947 activationFunction = ActivationFn::kActivationNone;
948 }
949 else
950 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100951 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100952 {
953 return Fail("%s: Operation has invalid inputs", __func__);
954 }
955 }
956 return true;
957}
958
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100959template<typename HalPolicy,
960 typename ConvolutionDescriptor,
961 typename HalOperation = typename HalPolicy::Operation,
962 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +0100963bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
964 uint32_t dilationXIndex,
965 ConvolutionDescriptor& descriptor,
966 const HalModel& model,
967 const ConversionData& data)
968{
969 bool success = true;
970 if (operation.inputs.size() >= dilationXIndex + 2)
971 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100972 success &= GetInputScalar<HalPolicy>(operation,
973 dilationXIndex,
974 HalPolicy::OperandType::INT32,
975 descriptor.m_DilationX,
976 model,
977 data);
978 success &= GetInputScalar<HalPolicy>(operation,
979 dilationXIndex + 1,
980 HalPolicy::OperandType::INT32,
981 descriptor.m_DilationY,
982 model,
983 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +0100984 }
985
986 return success;
987}
988
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100989template<typename HalPolicy,
990 typename HalOperand = typename HalPolicy::Operand,
991 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100992bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +0100993 std::vector<int32_t>& outValues,
994 const HalModel& model,
995 const ConversionData& data)
996{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100997 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100998 {
999 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1000 }
1001
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001002 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001003 if (!startAddress)
1004 {
1005 return Fail("%s: failed to get operand address", __func__, operand.type);
1006 }
1007
1008 // Check number of bytes is sensible
1009 const uint32_t numBytes = operand.location.length;
1010 if (numBytes % sizeof(int32_t) != 0)
1011 {
1012 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1013 __func__, numBytes, sizeof(int32_t));
1014 }
1015
1016 outValues.resize(numBytes / sizeof(int32_t));
1017 memcpy(outValues.data(), startAddress, numBytes);
1018 return true;
1019}
1020
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001021template<typename HalPolicy,
1022 typename HalOperation = typename HalPolicy::Operation,
1023 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001024bool GetInputPaddingScheme(const HalOperation& operation,
1025 uint32_t inputIndex,
1026 PaddingScheme& outPaddingScheme,
1027 const HalModel& model,
1028 const ConversionData& data)
1029{
1030 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001031 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001032 {
1033 return Fail("%s: failed to get padding scheme input value", __func__);
1034 }
1035
1036 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1037 return true;
1038}
1039
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001040template<typename HalPolicy,
1041 typename HalOperation = typename HalPolicy::Operation,
1042 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001043LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1044 uint32_t inputIndex,
1045 const HalModel& model,
1046 ConversionData& data)
1047{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001048 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001049 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001050 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1051
1052 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001053 if (!operand)
1054 {
1055 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1056 return LayerInputHandle();
1057 }
1058
1059 if (!IsOperandTypeSupportedForTensors(operand->type))
1060 {
1061 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1062 return LayerInputHandle();
1063 }
1064
Sadik Armagan44bcc022019-06-18 17:21:36 +01001065 try
arovir01b0717b52018-09-05 17:03:25 +01001066 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001067 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001068 if (IsDynamicTensor(operandTensorInfo))
1069 {
1070 Fail("%s: dynamic input tensors are not supported", __func__);
1071 return LayerInputHandle();
1072 }
arovir01b0717b52018-09-05 17:03:25 +01001073
Sadik Armagan44bcc022019-06-18 17:21:36 +01001074 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001075 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001076 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001077 {
1078 // NOTE: We must check whether we can support the input tensor on at least one
1079 // of the provided backends; otherwise we cannot convert the operation
1080 bool isInputSupported = false;
1081 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1082 IsInputSupported,
1083 data.m_Backends,
1084 isInputSupported,
1085 operandTensorInfo);
1086
1087 if (!isInputSupported)
1088 {
1089 Fail("%s: unsupported input tensor", __func__);
1090 return LayerInputHandle();
1091 }
1092
1093 BOOST_FALLTHROUGH; // intentional fallthrough
1094 }
1095 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001096 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001097 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001098 // The tensor is either an operand internal to the model, or a model input.
1099 // It can be associated with an ArmNN output slot for an existing layer.
1100
1101 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1102 const uint32_t operandIndex = operation.inputs[inputIndex];
1103 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001104 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001105 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001106 case HalOperandLifeTime::CONSTANT_REFERENCE:
1107 {
1108 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1109 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1110 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001111 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001112 bool isSupported = false;
1113 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1114 IsConstantSupported,
1115 data.m_Backends,
1116 isSupported,
1117 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001118 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001119 {
1120 return LayerInputHandle();
1121 }
1122
1123 armnn::IConnectableLayer* constantLayer =
1124 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1125 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1126 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1127
1128 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1129 }
1130 else
1131 {
1132 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001133 return LayerInputHandle();
1134 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001135 break;
arovir01b0717b52018-09-05 17:03:25 +01001136 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001137 default:
arovir01b0717b52018-09-05 17:03:25 +01001138 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001139 // Unsupported lifetime for an input tensor
1140 Fail("%s: unsupported lifetime for input tensor: %s",
1141 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001142 return LayerInputHandle();
1143 }
arovir01b0717b52018-09-05 17:03:25 +01001144 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001145 }
1146 catch (UnsupportedOperand<HalOperandType>& e)
1147 {
1148 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1149 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001150 }
1151}
1152
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001153template<typename HalPolicy,
1154 typename HalOperation = typename HalPolicy::Operation,
1155 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001156bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1157 uint32_t operationOutputIndex,
1158 armnn::IConnectableLayer& layer,
1159 uint32_t layerOutputIndex,
1160 const HalModel& model,
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001161 ConversionData& data)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001162{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001163 using HalOperand = typename HalPolicy::Operand;
1164
1165 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001166 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1167 {
1168 return false;
1169 }
1170
1171 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
1172
1173 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1174 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1175
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001176 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
Mike Kellyb5fdf382019-06-11 16:35:25 +01001177
1178 return true;
1179}
1180
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001181template<typename HalPolicy,
1182 typename HalOperation = typename HalPolicy::Operation,
1183 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001184armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1185 uint32_t inputIndex,
1186 const HalModel& model,
1187 ConversionData& data)
1188{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001189 using HalOperand = typename HalPolicy::Operand;
1190
1191 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001192 if (!operand)
1193 {
1194 return armnn::DataLayout::NHWC;
1195 }
1196
1197 if (!IsBool(*operand))
1198 {
1199 return armnn::DataLayout::NHWC;
1200 }
1201
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001202 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001203 if (!valueAddress)
1204 {
1205 return armnn::DataLayout::NHWC;
1206 }
1207
1208 if (*(static_cast<const bool*>(valueAddress)))
1209 {
1210 return armnn::DataLayout::NCHW;
1211 }
1212 else
1213 {
1214 return armnn::DataLayout::NHWC;
1215 }
1216}
1217
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001218template<typename HalPolicy,
1219 typename HalOperation = typename HalPolicy::Operation,
1220 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001221bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1222 uint32_t outputIndex,
1223 armnn::IConnectableLayer& layer,
1224 const HalModel& model,
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001225 ConversionData& data)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001226{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001227 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1228 outputIndex,
1229 layer,
1230 outputIndex,
1231 model,
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001232 data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001233}
1234
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001235template<typename HalPolicy,
1236 typename HalOperation = typename HalPolicy::Operation,
1237 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001238bool ConvertToActivation(const HalOperation& operation,
1239 const char* operationName,
1240 const armnn::ActivationDescriptor& activationDesc,
1241 const HalModel& model,
1242 ConversionData& data)
1243{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001244 using HalOperand = typename HalPolicy::Operand;
1245
1246 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001247 if (!input.IsValid())
1248 {
1249 return Fail("%s: Input 0 is invalid", operationName);
1250 }
1251
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001252 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001253 if (!outputOperand)
1254 {
1255 return false;
1256 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001257
1258 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Sadik Armagan2050c232019-07-23 16:59:58 +01001259 if (IsDynamicTensor(outInfo))
1260 {
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001261 return Fail("%s: Dynamic output tensors are not supported", __func__);
Sadik Armagan2050c232019-07-23 16:59:58 +01001262 }
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001263
1264 bool isSupported = false;
1265 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1266 IsActivationSupported,
1267 data.m_Backends,
1268 isSupported,
1269 input.GetTensorInfo(),
1270 outInfo,
1271 activationDesc);
1272 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001273 {
1274 return false;
1275 }
1276
1277 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
1278 BOOST_ASSERT(layer != nullptr);
1279 input.Connect(layer->GetInputSlot(0));
1280
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001281 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001282}
1283
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001284template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001285 typename HalOperation = typename HalPolicy::Operation,
1286 typename HalModel = typename HalPolicy::Model>
1287bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1288{
1289 armnn::ActivationDescriptor desc;
1290 desc.m_Function = armnn::ActivationFunction::ReLu;
1291
1292 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1293}
1294
1295template<typename HalPolicy,
1296 typename HalOperation = typename HalPolicy::Operation,
1297 typename HalModel = typename HalPolicy::Model>
1298bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1299{
1300 armnn::ActivationDescriptor desc;
1301 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1302 desc.m_A = 1.0f;
1303 desc.m_B = -1.0f;
1304
1305 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1306}
1307
1308template<typename HalPolicy,
1309 typename HalOperation = typename HalPolicy::Operation,
1310 typename HalModel = typename HalPolicy::Model>
1311bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1312{
1313 armnn::ActivationDescriptor desc;
1314 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1315 desc.m_A = 6.0f;
1316
1317 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1318}
1319
1320template<typename HalPolicy,
1321 typename HalOperation = typename HalPolicy::Operation,
1322 typename HalModel = typename HalPolicy::Model>
1323bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1324{
1325 armnn::ActivationDescriptor desc;
1326 desc.m_Function = armnn::ActivationFunction::TanH;
1327 desc.m_A = 1.0f; // android nn does not support tanH parameters
1328 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1329
1330 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1331}
1332
1333template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001334 typename HalOperation = typename HalPolicy::Operation,
1335 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001336bool ConvertPaddings(const HalOperation& operation,
1337 const HalModel& model,
1338 ConversionData& data,
1339 unsigned int rank,
1340 armnn::PadDescriptor& padDescriptor)
1341{
1342 using HalOperand = typename HalPolicy::Operand;
1343
1344 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1345 if (!paddingsOperand)
1346 {
1347 return Fail("%s: Could not read paddings operand", __func__);
1348 }
1349
1350 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1351 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1352 {
1353 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1354 }
1355
1356 std::vector<int32_t> paddings;
1357 GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data);
1358
1359 // add padding for each dimension of input tensor.
1360 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1361 {
1362 int paddingBeforeInput = paddings[i];
1363 int paddingAfterInput = paddings[i + 1];
1364
1365 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1366 {
1367 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1368 }
1369
1370 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1371 }
1372
1373 return true;
1374}
1375
1376template<typename HalPolicy,
1377 typename HalOperation = typename HalPolicy::Operation,
1378 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001379bool ConvertPooling2d(const HalOperation& operation,
1380 const char* operationName,
1381 armnn::PoolingAlgorithm poolType,
1382 const HalModel& model,
1383 ConversionData& data)
1384{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001385 using HalOperand = typename HalPolicy::Operand;
1386 using HalOperandType = typename HalPolicy::OperandType;
1387
1388 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001389 if (!input.IsValid())
1390 {
FinnWilliamsArm54c59752019-11-25 16:02:07 +00001391 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001392 }
1393
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001394 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001395 if (!output)
1396 {
1397 return Fail("%s: Could not read output 0", __func__);
1398 }
1399
1400 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1401 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1402
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001403 if (IsDynamicTensor(outputInfo))
1404 {
1405 return Fail("%s: Dynamic output tensors are not supported", __func__);
1406 }
1407
arovir01b0717b52018-09-05 17:03:25 +01001408 armnn::Pooling2dDescriptor desc;
1409 desc.m_PoolType = poolType;
1410 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001411 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001412
1413 ActivationFn activation;
1414
Sadik Armagan15d63e22019-07-26 16:59:35 +01001415 auto inputSize = operation.inputs.size();
1416
1417 if (inputSize >= 10)
1418 {
1419 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1420 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1421 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1422 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1423 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1424 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1425 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1426 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1427 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1428 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1429 {
1430 return Fail("%s: Operation has invalid inputs", operationName);
1431 }
1432
1433 if (Is12Operand(*output))
1434 {
1435 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1436 }
1437 }
1438 else
arovir01b0717b52018-09-05 17:03:25 +01001439 {
1440 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1441 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001442 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1443 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1444 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1445 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1446 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1447 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001448 {
1449 return Fail("%s: Operation has invalid inputs", operationName);
1450 }
1451
Sadik Armagan15d63e22019-07-26 16:59:35 +01001452 if (Is12Operand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001453 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001454 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001455 }
FinnWilliamsArm54c59752019-11-25 16:02:07 +00001456
1457 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1458 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1459 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1460
1461 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1462 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001463 }
1464
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001465 bool isSupported = false;
1466 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1467 IsPooling2dSupported,
1468 data.m_Backends,
1469 isSupported,
1470 inputInfo,
1471 outputInfo,
1472 desc);
1473 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001474 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001475 return false;
arovir01b0717b52018-09-05 17:03:25 +01001476 }
arovir01b0717b52018-09-05 17:03:25 +01001477
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001478 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1479 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001480 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001481 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001482 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001483
1484 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1485 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001486 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001487 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001488 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001489
1490 input.Connect(pooling2dLayer->GetInputSlot(0));
1491
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001492 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001493}
1494
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001495template<typename HalPolicy,
Mike Kellyb8805202019-07-31 17:25:43 +01001496 typename Operation = typename HalPolicy::Operation,
1497 typename Model = typename HalPolicy::Model>
Mike Kelly46272802019-08-14 17:00:48 +01001498bool ConvertAdd(const Operation& operation, const Model& model, ConversionData& data)
1499{
1500 using Operand = typename HalPolicy::Operand;
1501
1502 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1503 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1504
1505 if (!input0.IsValid() || !input1.IsValid())
1506 {
1507 return Fail("%s: Operation has invalid inputs", __func__);
1508 }
1509
1510 // The FuseActivation parameter is always the input index 2
1511 // and it should be optional
1512 ActivationFn activationFunction;
1513 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1514 {
1515 return Fail("%s: Operation has invalid inputs", __func__);
1516 }
1517
1518 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1519 if (!outputOperand)
1520 {
1521 return false;
1522 }
1523
1524 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1525 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1526
1527 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
1528 if (IsDynamicTensor(outputInfo))
1529 {
1530 return Fail("%s: Dynamic output tensors are not supported", __func__);
1531 }
1532
1533 bool isSupported = false;
1534 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1535 IsAdditionSupported,
1536 data.m_Backends,
1537 isSupported,
1538 inputInfo0,
1539 inputInfo1,
1540 outputInfo);
1541 if (!isSupported)
1542 {
1543 return false;
1544 }
1545
1546 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
1547 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
1548
1549 if (endLayer != nullptr)
1550 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01001551 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1552 if (!isReshapeSupported)
1553 {
1554 return false;
1555 }
1556
Mike Kelly46272802019-08-14 17:00:48 +01001557 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
1558 }
1559 else
1560 {
1561 return Fail("%s: ProcessActivation failed", __func__);
1562 }
1563}
1564
1565template<typename HalPolicy,
1566 typename Operation = typename HalPolicy::Operation,
1567 typename Model = typename HalPolicy::Model>
Francis Murtagha23334e2019-11-19 12:06:47 +00001568bool ConvertArgMinMax(const Operation& operation,
1569 const Model& model,
1570 ConversionData& data,
1571 armnn::ArgMinMaxFunction argMinMaxFunction)
1572{
1573 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1574
1575 using HalOperand = typename HalPolicy::Operand;
1576 using HalOperandType = typename HalPolicy::OperandType;
1577
1578 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1579
1580 if (!input0.IsValid())
1581 {
1582 return Fail("%s: Operation has invalid inputs", __func__);
1583 }
1584
1585 int32_t axis;
1586 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1587 {
1588 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1589 }
1590
1591 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1592 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1593
1594 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1595 {
1596 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1597 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1598 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1599 return Fail("%s: Axis must be in range [-n, n)", __func__);
1600 }
1601
1602 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1603 if (!output)
1604 {
1605 return Fail("%s: Could not read output 0", __func__);
1606 }
1607
1608 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1609
1610 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1611 if (IsDynamicTensor(outputInfo))
1612 {
1613 return Fail("%s: Dynamic output tensors are not supported", __func__);
1614 }
1615
1616 armnn::ArgMinMaxDescriptor descriptor;
1617 descriptor.m_Function = argMinMaxFunction;
1618 descriptor.m_Axis = axis;
1619
1620 bool isSupported = false;
1621 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1622 IsArgMinMaxSupported,
1623 data.m_Backends,
1624 isSupported,
1625 inputInfo0,
1626 outputInfo,
1627 descriptor);
1628 if (!isSupported)
1629 {
1630 return false;
1631 }
1632
1633 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1634 assert(layer != nullptr);
1635
1636 input0.Connect(layer->GetInputSlot(0));
1637
1638 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
1639}
1640
1641template<typename HalPolicy,
1642 typename Operation = typename HalPolicy::Operation,
1643 typename Model = typename HalPolicy::Model>
Mike Kellyb8805202019-07-31 17:25:43 +01001644bool ConvertConcatenation(const Operation& operation, const Model& model, ConversionData& data)
1645{
1646 using HalOperand = typename HalPolicy::Operand;
1647 using HalOperandType = typename HalPolicy::OperandType;
1648
1649 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1650 if (operation.inputs.size() <= 1)
1651 {
1652 return Fail("%s: Operation has insufficient arguments", __func__);
1653 }
1654
1655 // Get inputs and outputs
1656 const std::size_t numInputTensors = operation.inputs.size() - 1;
1657
1658 int32_t concatDim;
1659 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1660 {
1661 return Fail("%s: Operation has invalid inputs", __func__);
1662 }
1663
1664 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1665 if (!outputOperand)
1666 {
1667 return Fail("%s: Operation has no outputs", __func__);
1668 }
1669
1670
1671 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
1672 armnn::TensorShape outputShape = outputInfo.GetShape();
1673
1674 //
1675 // handle negative concat dims along the lines of tensorflow as described here:
1676 // https://www.tensorflow.org/api_docs/python/tf/concat
1677 // "negative axis refers to axis + rank(values)-th dimension"
1678 //
1679 if (concatDim < 0)
1680 {
1681 concatDim += outputShape.GetNumDimensions();
1682 }
1683
1684 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
1685 {
1686 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
1687 }
1688
1689 std::vector<LayerInputHandle> inputHandles;
1690 std::vector<armnn::TensorShape> inputShapes;
1691
1692 inputHandles.reserve(numInputTensors);
1693 inputShapes.reserve(numInputTensors);
1694
1695 bool inputsHaveBeenReshaped = false;
1696 unsigned int tensorDimensionsAdded = 0;
1697
1698 for (uint32_t i = 0; i < numInputTensors; ++i)
1699 {
1700 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
1701 if (!operand)
1702 {
1703 return Fail("%s: Operation has invalid inputs", __func__);
1704 }
1705
Teresa Charlin3b959602019-10-31 17:05:47 +00001706 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
1707 if (!operandInputHandle.IsValid())
1708 {
1709 return Fail("%s: Operation has invalid inputs", __func__);
1710 }
Mike Kellyb8805202019-07-31 17:25:43 +01001711
Teresa Charlin3b959602019-10-31 17:05:47 +00001712 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01001713 if (operandShape.GetNumDimensions() == 0)
1714 {
1715 return Fail("%s: Operands with rank 0 are not supported", __func__);
1716 }
1717
1718 if (RequiresReshape(operandShape))
1719 {
1720 inputsHaveBeenReshaped = true;
1721
1722 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
1723
1724 // Expand the tensor to three dimensions
1725 if (operandShape.GetNumDimensions() == 2)
1726 {
1727 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
1728 tensorDimensionsAdded = 1;
1729 }
1730 else
1731 {
1732 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
1733 tensorDimensionsAdded = 2;
1734 }
1735
1736 armnn::IConnectableLayer& newReshape = AddReshapeLayer(
1737 *data.m_Network,
1738 operandInputHandle,
1739 reshapeInfo
1740 );
1741
1742 // Point to the reshape operation rather then the input operation
1743 operandShape = reshapeInfo.GetShape();
1744 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
1745 }
1746
1747 inputShapes.emplace_back(operandShape);
1748 inputHandles.emplace_back(operandInputHandle);
1749
1750 if (!inputHandles.back().IsValid())
1751 {
1752 return Fail("%s: Operation has invalid inputs", __func__);
1753 }
1754 }
1755
1756 BOOST_ASSERT(inputShapes.size() == inputHandles.size());
1757
1758 if (inputsHaveBeenReshaped)
1759 {
1760 // Adjust the concatenation dimension by the amount of dimensions added (if any)
1761 concatDim += tensorDimensionsAdded;
1762
1763 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
1764 if (tensorDimensionsAdded == 1)
1765 {
1766 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
1767 }
1768 else if (tensorDimensionsAdded == 2)
1769 {
1770 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
1771 }
1772 }
1773
1774 // Check if permutations is required and get the pair of permutations required for the concatenation.
1775 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
1776 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
1777 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
1778
1779 bool needPermute =
1780 CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(), concatDim, permutationPair);
1781
1782 if (needPermute)
1783 {
1784 outputShape = armnnUtils::Permuted(outputShape, permutationPair.first);
1785 }
1786
1787 outputInfo.SetShape(outputShape);
1788
1789 // this is no-op for identity swizzles, otherwise it replaces both
1790 // the handles and shapes with the swizzled layer output handles and shapes
1791 SwizzleInputs(*data.m_Network, inputHandles, inputShapes, permutationPair.first);
1792
1793 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
1794 armnn::OriginsDescriptor concatDescriptor;
1795
1796 try
1797 {
1798 // The concat descriptor is always created across the only supported concat dimension
1799 // which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
1800 concatDescriptor =
1801 armnn::CreateDescriptorForConcatenation(inputShapes.begin(), inputShapes.end(), concatDim);
1802 }
1803 catch (const armnn::Exception& error)
1804 {
1805 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
1806 }
1807
1808 // Validate the output shape is correct given the input shapes based on the
1809 // only valid concat dimension which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
1810 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
1811 {
1812 return Fail("%s: Error validating the output shape for concat", __func__);
1813 }
1814
1815 std::vector<const armnn::TensorInfo*> inputTensorInfos;
1816 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
1817 [](const LayerInputHandle& h) -> const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
1818
1819 bool isSupported = false;
1820 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1821 IsConcatSupported,
1822 data.m_Backends,
1823 isSupported,
1824 inputTensorInfos,
1825 outputInfo,
1826 concatDescriptor);
1827 if (!isSupported)
1828 {
1829 return false;
1830 }
1831
1832 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
1833 assert(layer != nullptr);
1834 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1835
1836 // Connect inputs to the layer
1837 const int numInputSlots = layer->GetNumInputSlots();
1838 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
1839 for (int i = 0; i < numInputSlots; ++i)
1840 {
1841 // connect the input directly to the merge (concat) layer
1842 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
1843 }
1844
1845 if (needPermute)
1846 {
1847 // Add permutation layer and connect the output to it, the permutation becomes the output layer
1848 armnn::IConnectableLayer& deswizzleLayer = AddPermuteLayer(*data.m_Network,
1849 layer->GetOutputSlot(0),
1850 permutationPair.second);
1851 layer = &deswizzleLayer;
1852 }
1853
1854 if (inputsHaveBeenReshaped)
1855 {
1856 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
1857
1858 // Undo the reshape knowing the amount of dimensions added
1859 if (tensorDimensionsAdded == 1)
1860 {
1861 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[1],
1862 afterConcatInfo.GetShape()[2] }));
1863 }
1864 else if (tensorDimensionsAdded == 2)
1865 {
1866 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[2] }));
1867 }
1868
1869 layer = &AddReshapeLayer(
1870 *data.m_Network,
1871 layer->GetOutputSlot(0),
1872 afterConcatInfo
1873 );
1874 }
1875
1876 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
1877}
1878
1879template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001880 typename HalOperation = typename HalPolicy::Operation,
1881 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001882bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1883{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001884 using HalOperand = typename HalPolicy::Operand;
1885 using HalOperandType = typename HalPolicy::OperandType;
1886
1887 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001888 if (!input.IsValid())
1889 {
1890 return Fail("%s: Operation has invalid inputs", __func__);
1891 }
1892
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001893 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001894 if (!output)
1895 {
1896 return Fail("%s: Could not read output 0", __func__);
1897 }
1898
1899 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001900 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001901
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001902 if (IsDynamicTensor(outputInfo))
1903 {
1904 return Fail("%s: Dynamic output tensors are not supported", __func__);
1905 }
1906
Mike Kellyb5fdf382019-06-11 16:35:25 +01001907 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001908 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
1909 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001910
1911 if (!weightsPin.IsValid() || !biasPin.IsValid())
1912 {
1913 return Fail("%s: Operation has invalid inputs", __func__);
1914 }
1915
1916 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001917 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01001918 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1919
1920 armnn::Convolution2dDescriptor desc;
1921 desc.m_DataLayout = armnn::DataLayout::NHWC;
1922 ActivationFn activation;
1923
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001924 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001925 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001926 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1927 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1928 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1929 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1930 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1931 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001932 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001933 {
1934 return Fail("%s: Operation has invalid inputs", __func__);
1935 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001936 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001937 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001938 {
1939 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001940 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1941 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1942 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001943 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001944 {
1945 return Fail("%s: Operation has invalid inputs", __func__);
1946 }
1947
1948 const uint32_t kernelX = weights.GetShape()[2];
1949 const uint32_t kernelY = weights.GetShape()[1];
1950 const uint32_t inputX = inputInfo.GetShape()[2];
1951 const uint32_t inputY = inputInfo.GetShape()[1];
1952
1953 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1954 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001955 }
1956 else
1957 {
1958 return Fail("%s: Unsupported number of operation inputs", __func__);
1959 }
1960
1961 desc.m_BiasEnabled = true;
1962 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1963
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001964 bool isSupported = false;
1965 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1966 IsConvolution2dSupported,
1967 data.m_Backends,
1968 isSupported,
1969 inputInfo,
1970 outputInfo,
1971 desc,
1972 weights.GetInfo(),
1973 biases);
1974 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001975 {
1976 return false;
1977 }
1978
1979 armnn::IConnectableLayer* startLayer =
1980 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1981
1982 if (!startLayer)
1983 {
1984 return Fail("%s: AddConvolution2dLayer failed", __func__);
1985 }
1986
1987 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1988
1989 if (!endLayer)
1990 {
1991 return Fail("%s: ProcessActivation failed", __func__);
1992 }
1993
1994 input.Connect(startLayer->GetInputSlot(0));
1995
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001996 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001997}
1998
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001999template<typename HalPolicy,
2000 typename HalOperation = typename HalPolicy::Operation,
2001 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002002bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2003{
2004 using HalOperand = typename HalPolicy::Operand;
2005 using HalOperandType = typename HalPolicy::OperandType;
2006
2007 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2008 if (!input.IsValid() )
2009 {
2010 return Fail("%s: Operation has invalid inputs", __func__);
2011 }
2012
2013 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2014 unsigned int rank = inputInfo.GetNumDimensions();
2015 if (rank != 4)
2016 {
2017 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2018 }
2019
2020 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2021 if (!output)
2022 {
2023 return Fail("%s: Could not read output 0", __func__);
2024 }
2025
2026 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2027 if (IsDynamicTensor(outputInfo))
2028 {
2029 return Fail("%s: Dynamic output tensors are not supported", __func__);
2030 }
2031
2032 armnn::DepthToSpaceDescriptor descriptor;
2033
2034 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2035 if (descriptor.m_BlockSize <= 1)
2036 {
2037 return Fail("%s: Block size must be at least 1 in all dimensions");
2038 }
2039
2040 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
2041 if (Is12Operand(*output))
2042 {
2043 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2044 }
2045
2046 bool isSupported = false;
2047 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2048 IsDepthToSpaceSupported,
2049 data.m_Backends,
2050 isSupported,
2051 inputInfo,
2052 outputInfo,
2053 descriptor);
2054 if (!isSupported)
2055 {
2056 return false;
2057 }
2058
2059 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2060 assert(layer != nullptr);
2061 input.Connect(layer->GetInputSlot(0));
2062
2063 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2064}
2065
2066template<typename HalPolicy,
2067 typename HalOperation = typename HalPolicy::Operation,
2068 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002069bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2070{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002071 using HalOperand = typename HalPolicy::Operand;
2072 using HalOperandType = typename HalPolicy::OperandType;
2073
2074 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002075
2076 if (!input.IsValid())
2077 {
2078 return Fail("%s: Operation has invalid inputs", __func__);
2079 }
2080
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002081 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002082
2083 if (!output)
2084 {
2085 return Fail("%s: Could not read output 0", __func__);
2086 }
2087
2088 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002089 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002090
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002091 if (IsDynamicTensor(outputInfo))
2092 {
2093 return Fail("%s: Dynamic output tensors are not supported", __func__);
2094 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002095
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002096 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002097 // 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 +01002098 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002099
2100 if (weightsOperand == nullptr)
2101 {
2102 return Fail("%s: Operand is invalid", __func__);
2103 }
2104 armnn::DepthwiseConvolution2dDescriptor desc;
2105 desc.m_DataLayout = armnn::DataLayout::NHWC;
2106
Mike Kellyb5fdf382019-06-11 16:35:25 +01002107 // Reinterpret weight data as [ H, W, I, M ]
2108 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2109 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002110 inputInfo.GetShape()[3],
2111 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002112
2113 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2114 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2115
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002116 const ConstTensorPin weightsPin =
2117 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2118 1,
2119 model,
2120 data,
2121 HWIMToMIHW,
2122 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002123
2124 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002125 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002126
2127 if (!weightsPin.IsValid() || !biasPin.IsValid())
2128 {
2129 return Fail("%s: Operation has invalid inputs", __func__);
2130 }
2131
2132 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2133 armnn::ConstTensor bias = biasPin.GetConstTensor();
2134 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2135
2136 ActivationFn activation;
2137
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002138 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002139 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002140 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2141 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2142 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2143 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2144 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2145 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002146 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002147 {
2148 return Fail("%s: Operation has invalid inputs", __func__);
2149 }
2150 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002151 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002152 {
2153 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002154 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2155 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2156 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002157 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002158 {
2159 return Fail("%s: Operation has invalid inputs", __func__);
2160 }
2161
2162 const uint32_t kernelX = weights.GetShape()[3];
2163 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002164 const uint32_t inputX = inputInfo.GetShape()[2];
2165 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002166
2167 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2168 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2169 }
2170 else
2171 {
2172 return Fail("%s: Unsupported number of operation inputs", __func__);
2173 }
2174
2175 desc.m_BiasEnabled = true;
2176 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2177
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002178 bool isSupported = false;
2179 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2180 IsDepthwiseConvolutionSupported,
2181 data.m_Backends,
2182 isSupported,
2183 inputInfo,
2184 outputInfo,
2185 desc,
2186 weights.GetInfo(),
2187 biases);
2188 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002189 {
2190 return false;
2191 }
2192
2193 armnn::IConnectableLayer* startLayer =
2194 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2195 if (!startLayer)
2196 {
2197 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2198 }
2199
2200 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2201 if (!endLayer)
2202 {
2203 return Fail("%s: ProcessActivation failed", __func__);
2204 }
2205
2206 input.Connect(startLayer->GetInputSlot(0));
2207
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002208 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
arovir01b0717b52018-09-05 17:03:25 +01002209}
2210
Mike Kelly3c673942019-07-25 09:26:06 +01002211template<typename HalPolicy,
Mike Kelly46272802019-08-14 17:00:48 +01002212 typename Operation = typename HalPolicy::Operation,
2213 typename Model = typename HalPolicy::Model>
2214bool ConvertDequantize(const Operation& operation, const Model& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002215{
Mike Kelly46272802019-08-14 17:00:48 +01002216 using Operand = typename HalPolicy::Operand;
2217
2218 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2219 if (!input.IsValid())
2220 {
2221 return Fail("%s: Operation has invalid input", __func__);
2222 }
2223
Sadik Armagan7a13acc2019-11-21 15:54:36 +00002224 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2225 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2226 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2227 {
2228 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2229 }
2230
Mike Kelly46272802019-08-14 17:00:48 +01002231 const Operand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2232 if (!outputOperand)
2233 {
2234 return Fail("%s: Operation has invalid outputs", __func__);
2235 }
2236
2237 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2238 if (IsDynamicTensor(outputInfo))
2239 {
2240 return Fail("%s: Dynamic output tensors are not supported", __func__);
2241 }
2242
2243 bool isSupported = false;
2244 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2245 IsDequantizeSupported,
2246 data.m_Backends,
2247 isSupported,
Sadik Armagan7a13acc2019-11-21 15:54:36 +00002248 inputInfo,
2249 outputInfo);
Mike Kelly46272802019-08-14 17:00:48 +01002250 if (!isSupported)
2251 {
2252 return false;
2253 }
2254
2255 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2256 assert(layer != nullptr);
2257 input.Connect(layer->GetInputSlot(0));
2258
2259 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2260}
2261
2262template<typename HalPolicy,
2263 typename Operation = typename HalPolicy::Operation,
2264 typename Model = typename HalPolicy::Model>
2265bool ConvertDiv(const Operation& operation, const Model& model, ConversionData& data)
2266{
2267 using Operand = typename HalPolicy::Operand;
2268
2269 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2270 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2271
2272 if (!input0.IsValid() || !input1.IsValid())
2273 {
2274 return Fail("%s: Operation has invalid inputs", __func__);
2275 }
2276
2277 // The FuseActivation parameter is always the input index 2
2278 // and it should be optional
2279 ActivationFn activationFunction;
2280 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2281 {
2282 return Fail("%s: Operation has invalid inputs", __func__);
2283 }
2284
2285 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2286 if (!output)
2287 {
2288 return Fail("%s: Could not read output 0", __func__);
2289 }
2290
2291 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2292 if (IsDynamicTensor(outputInfo))
2293 {
2294 return Fail("%s: Dynamic output tensors are not supported", __func__);
2295 }
2296
2297 bool isSupported = false;
2298 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2299 IsDivisionSupported,
2300 data.m_Backends,
2301 isSupported,
2302 input0.GetTensorInfo(),
2303 input1.GetTensorInfo(),
2304 outputInfo);
2305 if (!isSupported)
2306 {
2307 return false;
2308 }
2309
2310 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
2311 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2312
2313 if (endLayer)
2314 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01002315 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2316 if (!isReshapeSupported)
2317 {
2318 return false;
2319 }
2320
Mike Kelly46272802019-08-14 17:00:48 +01002321 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2322 }
2323 return Fail("%s: ProcessActivation failed", __func__);
2324}
2325
2326template<typename HalPolicy,
2327 typename Operation = typename HalPolicy::Operation,
2328 typename Model = typename HalPolicy::Model>
2329bool ConvertFloor(const Operation& operation, const Model& model, ConversionData& data)
2330{
2331 using Operand = typename HalPolicy::Operand;
2332
2333 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2334 if (!input.IsValid())
2335 {
2336 return Fail("%s: Operation has invalid inputs", __func__);
2337 }
2338
2339 const Operand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2340 if (!outputOperand)
2341 {
2342 return Fail("%s: Operation has invalid outputs", __func__);
2343 }
2344
2345 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2346 if (IsDynamicTensor(outputInfo))
2347 {
2348 return Fail("%s: Dynamic output tensors are not supported", __func__);
2349 }
2350
2351 bool isSupported = false;
2352 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2353 IsFloorSupported,
2354 data.m_Backends,
2355 isSupported,
2356 input.GetTensorInfo(),
2357 outputInfo);
2358 if (!isSupported)
2359 {
2360 return false;
2361 }
2362
2363 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2364 assert(layer != nullptr);
2365 input.Connect(layer->GetInputSlot(0));
2366
2367 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2368}
2369
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002370inline bool IsQSymm8(const V1_0::Operand&)
2371{
2372 return false;
2373}
2374
2375#ifdef ARMNN_ANDROID_NN_V1_2
2376
2377inline bool IsQSymm8(const V1_2::Operand& operand)
2378{
2379 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2380}
2381
2382#endif
2383
2384template<typename HalPolicy,
2385 typename Operation = typename HalPolicy::Operation,
2386 typename Model = typename HalPolicy::Model>
Sadik Armaganac23b032019-11-18 17:11:21 +00002387std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, int>
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002388DequantizeIfRequired(size_t operand_index, const Operation& operation, const Model& model, const ConversionData& data)
2389{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002390 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002391
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002392 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armaganac23b032019-11-18 17:11:21 +00002393 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002394 {
Sadik Armaganac23b032019-11-18 17:11:21 +00002395 // Invalid Operand will return with error code '-1'
2396 return { nullptr, 0, armnn::TensorInfo(), -1 };
2397 }
2398
2399 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2400 {
2401 // Weights are already constant
2402 return { nullptr, 0, armnn::TensorInfo(), 0 };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002403 }
2404
2405 const size_t weightsInputIndex = operation.inputs[operand_index];
2406
2407 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2408 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
2409 for (uint32_t operationIdx = 0; operationIdx < model.operations.size(); ++operationIdx)
2410 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002411 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002412 const auto& operationIt = model.operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002413 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2414 {
2415 continue;
2416 }
2417
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002418 size_t outOpIndex = weightsInputIndex + 1;
2419 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002420 {
2421 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002422 }
2423
2424 if (outOpIndex != weightsInputIndex)
2425 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002426 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002427 }
2428
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002429 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002430 BOOST_ASSERT(operand);
2431
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002432 if (!IsQSymm8(*operand))
2433 {
2434 // Only supporting dequantize from QSYMM8 to FLOAT
2435 break;
2436 }
2437
2438 // Allocate a new buffer for the dequantized data and manually dequantize
2439 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2440 if (!startValue)
2441 {
2442 // Failed to get the operand address
2443 break;
2444 }
2445
2446 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2447 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002448 const float quantizationScale = operand->scale;
2449
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002450 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2451 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2452 {
2453 float* dstPtr = dequantizedBuffer.get();
2454 BOOST_ASSERT(dstPtr);
2455 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2456 }
2457
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002458 // Construct tensor info for dequantized ConstTensor
2459 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2460 operand->dimensions.data(),
2461 armnn::DataType::Float32);
2462
Sadik Armaganac23b032019-11-18 17:11:21 +00002463 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float), std::move(tensorInfo), 0 };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002464 }
2465
Sadik Armaganac23b032019-11-18 17:11:21 +00002466 return { nullptr, 0, armnn::TensorInfo() , 0};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002467}
2468
2469template<typename HalPolicy,
2470 typename Operation = typename HalPolicy::Operation,
2471 typename Model = typename HalPolicy::Model>
2472ConstTensorPin DequantizeAndMakeConstTensorPin(const Operation& operation,
2473 const Model& model,
2474 const ConversionData& data,
2475 size_t operandIndex,
2476 bool optional = false)
2477{
2478 auto dequantized = DequantizeIfRequired<HalPolicy, Operation, Model>(operandIndex,operation, model, data);
Sadik Armaganac23b032019-11-18 17:11:21 +00002479 if (std::get<3>(dequantized) == -1)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002480 {
Sadik Armaganac23b032019-11-18 17:11:21 +00002481 // Return it as invalid, tensor with no values is not really an error
2482 return ConstTensorPin();
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002483 }
2484
Sadik Armaganac23b032019-11-18 17:11:21 +00002485 if (std::get<1>(dequantized) == 0)
2486 {
2487 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2488 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
2489
2490 }
2491
2492 return ConstTensorPin(std::get<2>(dequantized), std::get<0>(dequantized).get(),
2493 std::get<1>(dequantized), g_DontPermute);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002494}
2495
2496
Mike Kelly46272802019-08-14 17:00:48 +01002497template<typename HalPolicy,
2498 typename Operation = typename HalPolicy::Operation,
2499 typename Model = typename HalPolicy::Model>
2500bool ConvertFullyConnected(const Operation& operation, const Model& model, ConversionData& data)
2501{
2502 using Operand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002503 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 Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2510 if (!output)
2511 {
2512 return Fail("%s: Could not read output 0", __func__);
2513 }
2514
2515 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2516 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2517
2518 if (IsDynamicTensor(outputInfo))
2519 {
2520 return Fail("%s: Dynamic output tensors are not supported", __func__);
2521 }
2522
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002523 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
2524 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002525
2526 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01002527 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002528 return Fail("%s: Operation has invalid weights", __func__);
2529 }
2530
2531 if (!biasPin.IsValid())
2532 {
2533 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01002534 }
2535
2536 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2537 armnn::ConstTensor bias = biasPin.GetConstTensor();
2538 armnn::TensorInfo reshapedInfo = inputInfo;
2539
2540 try
2541 {
2542 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002543 }
2544 catch (const std::exception& e)
2545 {
Mike Kelly46272802019-08-14 17:00:48 +01002546 return Fail("%s: %s", __func__, e.what());
2547 }
2548
2549 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
2550 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
2551
2552 ActivationFn activationFunction;
2553 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
2554 {
2555 return Fail("%s: Operation has invalid inputs", __func__);
2556 }
2557
2558 armnn::FullyConnectedDescriptor desc;
2559 desc.m_TransposeWeightMatrix = true;
2560 desc.m_BiasEnabled = true;
2561
2562 bool isSupported = false;
2563 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2564 IsFullyConnectedSupported,
2565 data.m_Backends,
2566 isSupported,
2567 reshapedInfo,
2568 outputInfo,
2569 weights.GetInfo(),
2570 bias.GetInfo(),
2571 desc);
2572 if (!isSupported)
2573 {
2574 return false;
2575 }
2576
2577 armnn::IConnectableLayer* startLayer =
2578 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2579 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2580
2581 if (endLayer != nullptr)
2582 {
2583 if (inputInfo.GetNumDimensions() > 2U)
2584 {
2585 armnn::ReshapeDescriptor reshapeDescriptor;
2586 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
2587
2588 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
2589 assert(reshapeLayer != nullptr);
2590 input.Connect(reshapeLayer->GetInputSlot(0));
2591 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
2592 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
2593 }
2594 else
2595 {
2596 input.Connect(startLayer->GetInputSlot(0));
2597 }
2598
2599 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2600 }
2601 else
2602 {
2603 return Fail("%s: ProcessActivation failed", __func__);
2604 }
2605}
2606
2607template<typename HalPolicy,
2608 typename Operation = typename HalPolicy::Operation,
2609 typename Model = typename HalPolicy::Model>
2610bool ConvertL2Normalization(const Operation& operation, const Model& model, ConversionData& data)
2611{
Mike Kelly999e2092019-08-15 10:46:46 +01002612 if (operation.inputs.size() != 1)
2613 {
2614 return Fail("%s: Optional inputs are not supported", __func__);
2615 }
2616
Mike Kelly46272802019-08-14 17:00:48 +01002617 using Operand = typename HalPolicy::Operand;
2618
2619 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2620 if (!input.IsValid())
2621 {
2622 return Fail("%s: Operation has invalid inputs", __func__);
2623 }
2624
2625 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2626 if (!output)
2627 {
2628 return Fail("%s: Could not read output 0", __func__);
2629 }
2630
2631 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2632 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2633
2634 if (IsDynamicTensor(outputInfo))
2635 {
2636 return Fail("%s: Dynamic output tensors are not supported", __func__);
2637 }
2638 if (outputInfo.GetNumDimensions() != 4u)
2639 {
2640 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
2641 }
2642
2643 armnn::L2NormalizationDescriptor desc;
2644 desc.m_DataLayout = armnn::DataLayout::NHWC;
2645
2646 bool isSupported = false;
2647 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2648 IsL2NormalizationSupported,
2649 data.m_Backends,
2650 isSupported,
2651 inputInfo,
2652 outputInfo,
2653 desc);
2654 if (!isSupported)
2655 {
2656 return false;
2657 }
2658
2659 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
2660 assert(layer != nullptr);
2661 input.Connect(layer->GetInputSlot(0));
2662
2663 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2664}
2665
2666template<typename HalPolicy,
2667 typename Operation = typename HalPolicy::Operation,
2668 typename Model = typename HalPolicy::Model>
2669bool ConvertLocalResponseNormalization(const Operation& operation,
2670 const Model& model,
2671 ConversionData& data)
2672{
Mike Kelly999e2092019-08-15 10:46:46 +01002673 if (operation.inputs.size() != 5)
2674 {
2675 return Fail("%s: Optional inputs are not supported", __func__);
2676 }
2677
Mike Kelly46272802019-08-14 17:00:48 +01002678 using Operand = typename HalPolicy::Operand;
2679 using OperandType = typename HalPolicy::OperandType;
2680
2681 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2682 if (!input.IsValid())
2683 {
2684 return Fail("%s: Operation has invalid inputs", __func__);
2685 }
2686
2687 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2688 if (!output)
2689 {
2690 return Fail("%s: Could not read output 0", __func__);
2691 }
2692
2693 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2694 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2695
2696 if (IsDynamicTensor(outputInfo))
2697 {
2698 return Fail("%s: Dynamic output tensors are not supported", __func__);
2699 }
2700 if (outputInfo.GetNumDimensions() != 4u)
2701 {
2702 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
2703 }
2704
2705 armnn::NormalizationDescriptor descriptor;
2706 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
2707 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
2708 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
2709
2710 if (!input.IsValid() ||
2711 !GetInputScalar<HalPolicy>(operation, 1, OperandType::INT32, descriptor.m_NormSize, model, data) ||
2712 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
2713 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
2714 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
2715 {
2716 return Fail("%s: Operation has invalid inputs", __func__);
2717 }
2718
2719 // ArmNN expects normSize to be the full size of the normalization
2720 // window rather than the radius as in AndroidNN.
2721 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
2722
2723 bool isSupported = false;
2724 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2725 IsNormalizationSupported,
2726 data.m_Backends,
2727 isSupported,
2728 inputInfo,
2729 outputInfo,
2730 descriptor);
2731 if (!isSupported)
2732 {
2733 return false;
2734 }
2735
2736
2737 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
2738 assert(layer != nullptr);
2739 input.Connect(layer->GetInputSlot(0));
2740
2741 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2742}
2743
2744template<typename HalPolicy,
2745 typename Operation = typename HalPolicy::Operation,
2746 typename Model = typename HalPolicy::Model>
2747bool ConvertLogistic(const Operation& operation, const Model& model, ConversionData& data)
2748{
2749 using Operand = typename HalPolicy::Operand;
2750
2751 armnn::ActivationDescriptor desc;
2752 desc.m_Function = armnn::ActivationFunction::Sigmoid;
2753
2754 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
2755}
2756
2757template<typename HalPolicy,
2758 typename Operation = typename HalPolicy::Operation,
2759 typename Model = typename HalPolicy::Model>
2760bool ConvertMean(const Operation& operation, const Model& model, ConversionData& data)
2761{
2762 using Operand = typename HalPolicy::Operand;
2763
2764 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2765 if (!input.IsValid())
2766 {
2767 return Fail("%s: Operation has invalid inputs", __func__);
2768 }
2769
2770 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2771 if (!output)
2772 {
2773 return Fail("%s: Could not read output 0", __func__);
2774 }
2775
2776 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2777 if (IsDynamicTensor(outputInfo))
2778 {
2779 return Fail("%s: Dynamic output tensors are not supported", __func__);
2780 }
2781
2782 const Operand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
2783 if (!axisOperand)
2784 {
2785 return Fail("%s: Could not read input 1", __func__);
2786 }
2787
2788 std::vector<int32_t> axis;
2789 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
2790 {
2791 return Fail("%s: Input 1 has invalid values", __func__);
2792 }
2793
2794 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2795
2796 // Convert the axis to unsigned int and remove duplicates.
2797 unsigned int rank = inputInfo.GetNumDimensions();
2798 std::set<unsigned int> uniqueAxis;
2799 std::transform(axis.begin(), axis.end(),
2800 std::inserter(uniqueAxis, uniqueAxis.begin()),
2801 [rank](int i) -> unsigned int { return (i + rank) % rank; });
2802
2803 // Get the "keep dims" flag.
2804 int32_t keepDims = 0;
2805 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
2806 {
2807 return Fail("%s: Could not read input 2", __func__);
2808 }
2809
2810 armnn::MeanDescriptor descriptor;
2811 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
2812 descriptor.m_KeepDims = keepDims > 0;
2813
2814 bool isSupported = false;
2815 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2816 IsMeanSupported,
2817 data.m_Backends,
2818 isSupported,
2819 inputInfo,
2820 outputInfo,
2821 descriptor);
2822 if (!isSupported)
2823 {
2824 return false;
2825 }
2826
2827 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
2828 assert(layer != nullptr);
2829 input.Connect(layer->GetInputSlot(0));
2830
2831 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2832}
2833
2834template<typename HalPolicy,
2835 typename Operation = typename HalPolicy::Operation,
2836 typename Model = typename HalPolicy::Model>
2837bool ConvertMul(const Operation& operation, const Model& model, ConversionData& data)
2838{
2839 using Operand = typename HalPolicy::Operand;
2840
2841 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2842 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2843
2844 if (!input0.IsValid() || !input1.IsValid())
2845 {
2846 return Fail("%s: Operation has invalid inputs", __func__);
2847 }
2848
2849 // The FuseActivation parameter is always the input index 2
2850 // and it should be optional
2851 ActivationFn activationFunction;
2852 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2853 {
2854 return Fail("%s: Operation has invalid inputs", __func__);
2855 }
2856
2857 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2858
2859 if (outputOperand == nullptr)
2860 {
2861 return false;
2862 }
2863
2864 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2865 if (IsDynamicTensor(outputInfo))
2866 {
2867 return Fail("%s: Dynamic output tensors are not supported", __func__);
2868 }
2869
2870 bool isSupported = false;
2871 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2872 IsMultiplicationSupported,
2873 data.m_Backends,
2874 isSupported,
2875 input0.GetTensorInfo(),
2876 input1.GetTensorInfo(),
2877 outputInfo);
2878 if (!isSupported)
2879 {
2880 return false;
2881 }
2882
2883 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
2884 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2885
2886 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
2887 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
2888
2889 if (endLayer != nullptr)
2890 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01002891 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2892 if (!isReshapeSupported)
2893 {
2894 return false;
2895 }
2896
Mike Kelly46272802019-08-14 17:00:48 +01002897 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2898 }
2899 else
2900 {
2901 return Fail("%s: ProcessActivation failed", __func__);
2902 }
2903}
2904
2905template<typename HalPolicy,
2906 typename Operation = typename HalPolicy::Operation,
2907 typename Model = typename HalPolicy::Model>
2908bool ConvertPad(Operation& operation, const Model& model, ConversionData& data)
2909{
2910 using Operand = typename HalPolicy::Operand;
2911
Mike Kelly3c673942019-07-25 09:26:06 +01002912 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2913 if (!input.IsValid())
2914 {
2915 return Fail("%s: Operation has invalid inputs", __func__);
2916 }
2917
2918 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2919 unsigned int rank = inputInfo.GetNumDimensions();
2920
2921 armnn::PadDescriptor descriptor;
2922 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
2923 {
2924 return Fail("%s: Could not convert paddings", __func__);
2925 }
2926
2927 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
2928 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
2929 // (QuantizationOffset - QuantizationOffset) * scale = 0.
2930 if (inputInfo.GetDataType() == armnn::DataType::QuantisedAsymm8)
2931 {
2932 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
2933 }
2934
Mike Kelly46272802019-08-14 17:00:48 +01002935 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01002936 if (!output)
2937 {
2938 return Fail("%s: Could not read output", __func__);
2939 }
2940
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002941 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01002942 if (IsDynamicTensor(outputInfo))
2943 {
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002944 return Fail("%s: Dynamic output tensors are not supported", __func__);
Mike Kelly3c673942019-07-25 09:26:06 +01002945 }
2946
2947 bool isSupported = false;
2948 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2949 IsPadSupported,
2950 data.m_Backends,
2951 isSupported,
2952 inputInfo,
2953 outputInfo,
2954 descriptor);
2955 if (!isSupported)
2956 {
2957 return false;
2958 }
2959
2960 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
2961 assert(layer != nullptr);
2962 input.Connect(layer->GetInputSlot(0));
2963 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2964
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002965 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
Mike Kelly3c673942019-07-25 09:26:06 +01002966}
2967
Mike Kelly0a879362019-07-29 16:56:31 +01002968template<typename HalPolicy,
2969 typename Operation = typename HalPolicy::Operation,
Mike Kelly46272802019-08-14 17:00:48 +01002970 typename Model = typename HalPolicy::Model>
2971bool ConvertReshape(const Operation& operation, const Model& model, ConversionData& data)
2972{
2973 using Operand = typename HalPolicy::Operand;
2974
2975 const Operand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
2976 const Operand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
2977 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2978
2979 if (inputOperand == nullptr
2980 || requestedShapeOperand == nullptr
2981 || outputOperand == nullptr)
2982 {
2983 return Fail("%s: Operation has invalid inputs", __func__);
2984 }
2985
2986 if (requestedShapeOperand->dimensions.size() != 1)
2987 {
2988 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
2989 __func__, requestedShapeOperand->dimensions.size());
2990 }
2991
2992 std::vector<int32_t> targetDimensions;
2993 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
2994 {
2995 return Fail("%s: Could not read values of input 1", __func__);
2996 }
2997
2998 const Shape inputOperandShape = GetOperandShape(*inputOperand);
2999
3000 Shape requestedShape;
3001 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3002 // function that resolves these values into a fully specified tensor shape.
3003 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3004 {
3005 return Fail("%s: Failed to resolve the requested shape", __func__);
3006 }
3007
3008 const Shape outputOperandShape = GetOperandShape(*outputOperand);
3009 if (!SameShape(requestedShape, outputOperandShape))
3010 {
3011 return Fail("%s: Shape of output operand does not match resolved requested shape", __func__);
3012 }
3013
3014 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3015 if (!input.IsValid())
3016 {
3017 return Fail("%s: Could not read input 0", __func__);
3018 }
3019
3020 armnn::ReshapeDescriptor reshapeDescriptor;
3021 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3022 requestedShape.dimensions.data());
3023
3024 bool isSupported = false;
3025 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3026 IsReshapeSupported,
3027 data.m_Backends,
3028 isSupported,
3029 input.GetTensorInfo(),
3030 reshapeDescriptor);
3031 if (!isSupported)
3032 {
3033 return false;
3034 }
3035
3036 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3037 assert(layer != nullptr);
3038 input.Connect(layer->GetInputSlot(0));
3039
3040 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3041}
3042
3043template<typename HalPolicy,
3044 typename Operation = typename HalPolicy::Operation,
Mike Kelly0a879362019-07-29 16:56:31 +01003045 typename Model = typename HalPolicy::Model>
3046bool ConvertSub(const Operation& operation, const Model& model, ConversionData& data)
3047{
Mike Kelly46272802019-08-14 17:00:48 +01003048 using Operand = typename HalPolicy::Operand;
3049
Mike Kelly0a879362019-07-29 16:56:31 +01003050 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3051 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3052
3053 if (!input0.IsValid() || !input1.IsValid())
3054 {
3055 return Fail("%s: Operation has invalid inputs", __func__);
3056 }
3057
3058 // The FuseActivation parameter is always the input index 2
3059 // and it should be optional
3060 ActivationFn activationFunction;
3061 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3062 {
3063 return Fail("%s: Operation has invalid inputs", __func__);
3064 }
3065
3066 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3067 if (!output)
3068 {
3069 return Fail("%s: Could not read output 0", __func__);
3070 }
3071
3072 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3073 if (IsDynamicTensor(outputInfo))
3074 {
3075 return Fail("%s: Dynamic output tensors are not supported", __func__);
3076 }
3077
3078 bool isSupported = false;
3079 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3080 IsSubtractionSupported,
3081 data.m_Backends,
3082 isSupported,
3083 input0.GetTensorInfo(),
3084 input1.GetTensorInfo(),
3085 outputInfo);
3086 if (!isSupported)
3087 {
3088 return false;
3089 }
3090
3091 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
3092 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3093
3094 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3095 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3096
3097 if (endLayer)
3098 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01003099 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3100 if (!isReshapeSupported)
3101 {
3102 return false;
3103 }
Mike Kelly0a879362019-07-29 16:56:31 +01003104 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
3105 }
3106
3107 return Fail("%s: ProcessActivation failed", __func__);
3108}
3109
Finn Williams23b87b32019-07-30 11:44:05 +01003110template<typename HalPolicy,
Mike Kelly46272802019-08-14 17:00:48 +01003111 typename Operation = typename HalPolicy::Operation,
3112 typename Model = typename HalPolicy::Model>
3113bool ConvertSqueeze(const Operation& operation, const Model& model, ConversionData& data)
3114{
3115 using Operand = typename HalPolicy::Operand;
3116
3117 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3118 if (!input.IsValid())
3119 {
3120 return Fail("%s: Operation has invalid inputs", __func__);
3121 }
3122
3123 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3124 unsigned int rank = inputInfo.GetNumDimensions();
3125 if (rank > 4)
3126 {
3127 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3128 }
3129
3130 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3131 if (!output)
3132 {
3133 return Fail("%s: Could not read output 0", __func__);
3134 }
3135
3136 if (IsDynamicTensor(GetTensorInfoForOperand(*output)))
3137 {
3138 return Fail("%s: Dynamic output tensors are not supported", __func__);
3139 }
3140
3141 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3142 // if the operand index is out of bounds.
3143 const Operand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
3144
3145 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3146
3147 std::vector<int32_t> axis;
3148 if (!axisOperand)
3149 {
3150 axis.assign(dimensionSequence,
3151 dimensionSequence + rank);
3152 }
3153 else
3154 {
3155 GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data);
3156 }
3157
3158 std::vector<uint32_t> outputDims;
3159 for (unsigned int i = 0; i < rank; i++)
3160 {
3161 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3162 auto currentDimension = inputInfo.GetShape()[i];
3163 if (skipSqueeze || currentDimension != 1)
3164 {
3165 outputDims.push_back(currentDimension);
3166 }
3167 }
3168
3169 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3170
3171 armnn::TensorInfo outputInfo = inputInfo;
3172 outputInfo.SetShape(outShape);
3173
3174 armnn::ReshapeDescriptor reshapeDesc;
3175 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3176
3177 bool isSupported = false;
3178 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3179 IsReshapeSupported,
3180 data.m_Backends,
3181 isSupported,
3182 inputInfo,
3183 reshapeDesc);
3184 if (!isSupported)
3185 {
3186 return false;
3187 }
3188
3189 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3190 assert(layer != nullptr);
3191 input.Connect(layer->GetInputSlot(0));
3192
3193 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3194}
3195
3196template<typename HalPolicy,
3197 typename Operation = typename HalPolicy::Operation,
3198 typename Model = typename HalPolicy::Model>
3199bool ConvertStridedSlice(const Operation& operation, const Model& model, ConversionData& data)
3200{
3201 using Operand = typename HalPolicy::Operand;
3202
3203 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3204 if (!input.IsValid())
3205 {
3206 return Fail("%s: Operation has invalid inputs", __func__);
3207 }
3208
3209 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3210 unsigned int rank = inputInfo.GetNumDimensions();
3211 if (rank > 4)
3212 {
3213 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3214 }
3215
3216 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3217 if (!output)
3218 {
3219 return Fail("%s: Could not read output 0", __func__);
3220 }
3221
3222 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3223 if (IsDynamicTensor(outputInfo))
3224 {
3225 return Fail("%s: Dynamic output tensors are not supported", __func__);
3226 }
3227
3228 const Operand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3229 const Operand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3230 const Operand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
3231
3232 std::vector<int32_t> beginValues;
3233 std::vector<int32_t> endValues;
3234 std::vector<int32_t> stridesValues;
3235
3236 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
3237 auto ValidateInputOperands = [&] (const Operand& operand, std::vector<int32_t>& operandValues)
3238 {
3239 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3240 {
3241 return false;
3242 }
3243
3244 if (operandValues.size() != rank)
3245 {
3246 return false;
3247 }
3248
3249 return true;
3250 };
3251
3252 if (!ValidateInputOperands(*beginOperand, beginValues)
3253 || !ValidateInputOperands(*endOperand, endValues)
3254 || !ValidateInputOperands(*stridesOperand, stridesValues))
3255 {
3256 return Fail("%s: Operation has invalid input operand", __func__);
3257 }
3258
3259 // Stride cannot have value '0'
3260 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3261 {
3262 return Fail("%s: Stride must be non-zero value.", __func__);
3263 }
3264
3265 armnn::StridedSliceDescriptor descriptor;
3266 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3267 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3268 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3269 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3270
3271 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3272 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3273 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3274 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3275 {
3276 return Fail("%s: Operation has invalid inputs", __func__);
3277 }
3278
3279 bool isSupported = false;
3280 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3281 IsStridedSliceSupported,
3282 data.m_Backends,
3283 isSupported,
3284 inputInfo,
3285 outputInfo,
3286 descriptor);
3287 if (!isSupported)
3288 {
3289 return false;
3290 }
3291
3292 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3293 assert(layer != nullptr);
3294 input.Connect(layer->GetInputSlot(0));
3295
3296 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3297}
3298
3299template<typename HalPolicy,
3300 typename Operation = typename HalPolicy::Operation,
3301 typename Model = typename HalPolicy::Model>
3302bool ConvertTranspose(const Operation& operation, const Model& model, ConversionData& data)
3303{
3304 using Operand = typename HalPolicy::Operand;
3305
3306 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3307 if (!input.IsValid())
3308 {
3309 return Fail("%s: Operation has invalid inputs", __func__);
3310 }
3311
3312 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3313 unsigned int rank = inputInfo.GetNumDimensions();
3314 if (rank > 4)
3315 {
3316 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3317 }
3318
3319 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3320 // if the operand index is out of bounds.
3321 const Operand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
3322
3323 std::vector<int32_t> perm(rank);
3324 if (!permOperand)
3325 {
3326 // NOTE: If perm is not given, it is set to (n-1...0), where n is the rank of the tensor
3327 for (unsigned int i = rank; i > 0; i--)
3328 {
3329 perm[rank - i] = boost::numeric_cast<int> (i - 1);
3330 }
3331 }
3332 else
3333 {
3334 GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data);
3335 }
3336
3337 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3338
3339 auto permutationVector = armnn::PermutationVector(outputDims.data(), outputDims.size());
3340 if (!permutationVector.IsEqual(NHWCToArmNN)
3341 && !permutationVector.IsEqual(ArmNNToNHWC)
3342 && !permutationVector.IsEqual({ 3, 2, 0, 1 }))
3343 {
3344 return Fail("%s: Only [0, 3, 1, 2], [0, 2, 3, 1] and [3, 2, 0, 1] permutations are supported.", __func__);
3345 }
3346
3347 armnn::PermuteDescriptor permuteDesc;
3348 permuteDesc.m_DimMappings = permutationVector;
3349
3350 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3351 if (!output)
3352 {
3353 return Fail("%s: Could not read output 0", __func__);
3354 }
3355
3356 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3357
3358 bool isSupported = false;
3359 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3360 IsPermuteSupported,
3361 data.m_Backends,
3362 isSupported,
3363 inputInfo,
3364 outputInfo,
3365 permuteDesc);
3366 if (!isSupported)
3367 {
3368 return false;
3369 }
3370
3371 armnn::IConnectableLayer* const layer = data.m_Network->AddPermuteLayer(permuteDesc);
3372 assert(layer != nullptr);
3373 input.Connect(layer->GetInputSlot(0));
3374
3375 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3376}
3377
3378template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003379 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003380 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003381 typename HalModel = typename HalPolicy::Model>
3382bool ConvertBatchToSpaceNd(const HalOperation& operation,
3383 const HalModel& model,
3384 ConversionData& data)
3385{
Finn Williams23b87b32019-07-30 11:44:05 +01003386
3387 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3388 if (!input.IsValid())
3389 {
3390 return Fail("%s: Operation has invalid inputs", __func__);
3391 }
3392
3393 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3394 if (!output)
3395 {
3396 return Fail("%s: Could not read output 0", __func__);
3397 }
3398
3399 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3400 if (IsDynamicTensor(outputInfo))
3401 {
3402 return Fail("%s: Dynamic output tensors are not supported", __func__);
3403 }
3404
3405 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3406 if (!blockOperand)
3407 {
3408 return Fail("%s: Could not read input 1", __func__);
3409 }
3410
3411 // Convert the block operand to int32
3412 std::vector<int32_t> block;
3413 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
3414 {
3415 return Fail("%s: Input 1 has invalid values", __func__);
3416 }
3417
3418 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3419
3420 unsigned int rank = inputInfo.GetNumDimensions();
3421 if (rank != 4)
3422 {
3423 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
3424 }
3425
3426 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
3427 {
3428 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
3429 " greater than or equal to 1", __func__);
3430 }
3431
3432 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
3433 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
3434 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
3435
3436 if (Is12Operand(*output))
3437 {
Finn Williams0e4e4392019-07-31 10:56:27 +01003438 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01003439 }
3440 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
3441 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
3442
3443 bool isSupported = false;
3444 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3445 IsBatchToSpaceNdSupported,
3446 data.m_Backends,
3447 isSupported,
3448 inputInfo,
3449 outputInfo,
3450 batchToSpaceNdDesc);
3451 if (!isSupported)
3452 {
3453 return false;
3454 }
3455
3456 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
3457 assert(layer != nullptr);
3458 input.Connect(layer->GetInputSlot(0));
3459
3460 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3461}
Mike Kelly0a879362019-07-29 16:56:31 +01003462
Finn Williamsd74c5052019-07-30 17:06:00 +01003463template<typename HalPolicy,
3464 typename HalOperation = typename HalPolicy::Operation,
3465 typename HalOperand = typename HalPolicy::Operand,
3466 typename HalModel = typename HalPolicy::Model>
3467bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
3468{
3469 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3470 if (!input.IsValid())
3471 {
3472 return Fail("%s: Operation has invalid inputs", __func__);
3473 }
3474
3475 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3476 unsigned int rank = inputInfo.GetNumDimensions();
3477 unsigned int spatialDim = rank - 2;
3478
3479 if (rank != 4)
3480 {
3481 Fail("%s: Only inputs with rank 4 are supported", __func__);
3482 }
3483
3484 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3485 if (!output)
3486 {
3487 return Fail("%s: Could not read output 0", __func__);
3488 }
3489
3490 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3491 if (IsDynamicTensor(outputInfo))
3492 {
3493 return Fail("%s: Dynamic output tensors are not supported", __func__);
3494 }
3495
3496 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3497 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3498
3499 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
3500 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
3501 {
3502 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
3503 }
3504
3505 std::vector<int32_t> blockShape;
3506 GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data);
3507 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
3508 {
3509 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
3510 }
3511
3512 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
3513 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
3514 {
3515 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
3516 }
3517
3518 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
3519 std::vector<int32_t> paddings;
3520 GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data);
3521 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
3522 {
3523 int paddingBeforeInput = paddings[i];
3524 int paddingAfterInput = paddings[i + 1];
3525 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
3526 {
3527 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
3528 }
3529
3530 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
3531 }
3532
3533 armnn::SpaceToBatchNdDescriptor descriptor;
3534 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3535 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
3536 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
3537
3538 if (Is12Operand(*output))
3539 {
3540 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
3541 }
3542
3543 bool isSupported = false;
3544 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3545 IsSpaceToBatchNdSupported,
3546 data.m_Backends,
3547 isSupported,
3548 inputInfo,
3549 outputInfo,
3550 descriptor);
3551 if (!isSupported)
3552 {
3553 return false;
3554 }
3555
3556 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
3557 assert(layer != nullptr);
3558 input.Connect(layer->GetInputSlot(0));
3559
3560 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3561}
3562
Kevin May407718f2019-09-09 14:46:41 +01003563template<typename HalPolicy,
3564 typename HalOperation = typename HalPolicy::Operation,
3565 typename HalModel = typename HalPolicy::Model>
3566bool ConvertAbs(const HalOperation& operation, const HalModel& model, ConversionData& data)
3567{
3568 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3569
3570 if (!input.IsValid())
3571 {
3572 return Fail("%s: Operation has invalid input", __func__);
3573 }
3574
3575 using HalOperand = typename HalPolicy::Operand;
3576 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3577 if (!output)
3578 {
3579 return Fail("%s: Could not read output 0", __func__);
3580 }
3581
3582 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3583 if (IsDynamicTensor(outputInfo))
3584 {
3585 return Fail("%s: Dynamic output tensors are not supported", __func__);
3586 }
3587
3588 bool isSupported = false;
3589 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3590 IsAbsSupported,
3591 data.m_Backends,
3592 isSupported,
3593 input.GetTensorInfo(),
3594 outputInfo);
3595
3596 if (!isSupported)
3597 {
3598 return false;
3599 }
3600
3601 armnn::IConnectableLayer* const layer = data.m_Network->AddAbsLayer();
3602 assert(layer != nullptr);
3603 input.Connect(layer->GetInputSlot(0));
3604
3605 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3606}
3607
3608
saoste01b8471482018-10-10 09:44:51 +01003609} // namespace armnn_driver