blob: 0637c2b540b8c35c522db78964290073efd2845e [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 {
1391 return Fail("%s: Could not read input 0", operationName);
1392 }
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
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001452 const unsigned int inputWidth = inputInfo.GetShape()[2];
1453 const unsigned int inputHeight = inputInfo.GetShape()[1];
arovir01b0717b52018-09-05 17:03:25 +01001454
1455 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1456 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
Sadik Armagan15d63e22019-07-26 16:59:35 +01001457
1458 if (Is12Operand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001459 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001460 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001461 }
1462 }
1463
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001464 bool isSupported = false;
1465 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1466 IsPooling2dSupported,
1467 data.m_Backends,
1468 isSupported,
1469 inputInfo,
1470 outputInfo,
1471 desc);
1472 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001473 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001474 return false;
arovir01b0717b52018-09-05 17:03:25 +01001475 }
arovir01b0717b52018-09-05 17:03:25 +01001476
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001477 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1478 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001479 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001480 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001481 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001482
1483 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1484 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001485 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001486 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001487 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001488
1489 input.Connect(pooling2dLayer->GetInputSlot(0));
1490
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001491 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001492}
1493
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001494template<typename HalPolicy,
Mike Kellyb8805202019-07-31 17:25:43 +01001495 typename Operation = typename HalPolicy::Operation,
1496 typename Model = typename HalPolicy::Model>
Mike Kelly46272802019-08-14 17:00:48 +01001497bool ConvertAdd(const Operation& operation, const Model& model, ConversionData& data)
1498{
1499 using Operand = typename HalPolicy::Operand;
1500
1501 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1502 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1503
1504 if (!input0.IsValid() || !input1.IsValid())
1505 {
1506 return Fail("%s: Operation has invalid inputs", __func__);
1507 }
1508
1509 // The FuseActivation parameter is always the input index 2
1510 // and it should be optional
1511 ActivationFn activationFunction;
1512 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1513 {
1514 return Fail("%s: Operation has invalid inputs", __func__);
1515 }
1516
1517 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1518 if (!outputOperand)
1519 {
1520 return false;
1521 }
1522
1523 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1524 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1525
1526 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
1527 if (IsDynamicTensor(outputInfo))
1528 {
1529 return Fail("%s: Dynamic output tensors are not supported", __func__);
1530 }
1531
1532 bool isSupported = false;
1533 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1534 IsAdditionSupported,
1535 data.m_Backends,
1536 isSupported,
1537 inputInfo0,
1538 inputInfo1,
1539 outputInfo);
1540 if (!isSupported)
1541 {
1542 return false;
1543 }
1544
1545 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
1546 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
1547
1548 if (endLayer != nullptr)
1549 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01001550 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
1551 if (!isReshapeSupported)
1552 {
1553 return false;
1554 }
1555
Mike Kelly46272802019-08-14 17:00:48 +01001556 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
1557 }
1558 else
1559 {
1560 return Fail("%s: ProcessActivation failed", __func__);
1561 }
1562}
1563
1564template<typename HalPolicy,
1565 typename Operation = typename HalPolicy::Operation,
1566 typename Model = typename HalPolicy::Model>
Mike Kellyb8805202019-07-31 17:25:43 +01001567bool ConvertConcatenation(const Operation& operation, const Model& model, ConversionData& data)
1568{
1569 using HalOperand = typename HalPolicy::Operand;
1570 using HalOperandType = typename HalPolicy::OperandType;
1571
1572 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1573 if (operation.inputs.size() <= 1)
1574 {
1575 return Fail("%s: Operation has insufficient arguments", __func__);
1576 }
1577
1578 // Get inputs and outputs
1579 const std::size_t numInputTensors = operation.inputs.size() - 1;
1580
1581 int32_t concatDim;
1582 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1583 {
1584 return Fail("%s: Operation has invalid inputs", __func__);
1585 }
1586
1587 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1588 if (!outputOperand)
1589 {
1590 return Fail("%s: Operation has no outputs", __func__);
1591 }
1592
1593
1594 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
1595 armnn::TensorShape outputShape = outputInfo.GetShape();
1596
1597 //
1598 // handle negative concat dims along the lines of tensorflow as described here:
1599 // https://www.tensorflow.org/api_docs/python/tf/concat
1600 // "negative axis refers to axis + rank(values)-th dimension"
1601 //
1602 if (concatDim < 0)
1603 {
1604 concatDim += outputShape.GetNumDimensions();
1605 }
1606
1607 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
1608 {
1609 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
1610 }
1611
1612 std::vector<LayerInputHandle> inputHandles;
1613 std::vector<armnn::TensorShape> inputShapes;
1614
1615 inputHandles.reserve(numInputTensors);
1616 inputShapes.reserve(numInputTensors);
1617
1618 bool inputsHaveBeenReshaped = false;
1619 unsigned int tensorDimensionsAdded = 0;
1620
1621 for (uint32_t i = 0; i < numInputTensors; ++i)
1622 {
1623 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
1624 if (!operand)
1625 {
1626 return Fail("%s: Operation has invalid inputs", __func__);
1627 }
1628
Teresa Charlin3b959602019-10-31 17:05:47 +00001629 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
1630 if (!operandInputHandle.IsValid())
1631 {
1632 return Fail("%s: Operation has invalid inputs", __func__);
1633 }
Mike Kellyb8805202019-07-31 17:25:43 +01001634
Teresa Charlin3b959602019-10-31 17:05:47 +00001635 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01001636 if (operandShape.GetNumDimensions() == 0)
1637 {
1638 return Fail("%s: Operands with rank 0 are not supported", __func__);
1639 }
1640
1641 if (RequiresReshape(operandShape))
1642 {
1643 inputsHaveBeenReshaped = true;
1644
1645 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
1646
1647 // Expand the tensor to three dimensions
1648 if (operandShape.GetNumDimensions() == 2)
1649 {
1650 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
1651 tensorDimensionsAdded = 1;
1652 }
1653 else
1654 {
1655 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
1656 tensorDimensionsAdded = 2;
1657 }
1658
1659 armnn::IConnectableLayer& newReshape = AddReshapeLayer(
1660 *data.m_Network,
1661 operandInputHandle,
1662 reshapeInfo
1663 );
1664
1665 // Point to the reshape operation rather then the input operation
1666 operandShape = reshapeInfo.GetShape();
1667 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
1668 }
1669
1670 inputShapes.emplace_back(operandShape);
1671 inputHandles.emplace_back(operandInputHandle);
1672
1673 if (!inputHandles.back().IsValid())
1674 {
1675 return Fail("%s: Operation has invalid inputs", __func__);
1676 }
1677 }
1678
1679 BOOST_ASSERT(inputShapes.size() == inputHandles.size());
1680
1681 if (inputsHaveBeenReshaped)
1682 {
1683 // Adjust the concatenation dimension by the amount of dimensions added (if any)
1684 concatDim += tensorDimensionsAdded;
1685
1686 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
1687 if (tensorDimensionsAdded == 1)
1688 {
1689 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
1690 }
1691 else if (tensorDimensionsAdded == 2)
1692 {
1693 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
1694 }
1695 }
1696
1697 // Check if permutations is required and get the pair of permutations required for the concatenation.
1698 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
1699 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
1700 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
1701
1702 bool needPermute =
1703 CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(), concatDim, permutationPair);
1704
1705 if (needPermute)
1706 {
1707 outputShape = armnnUtils::Permuted(outputShape, permutationPair.first);
1708 }
1709
1710 outputInfo.SetShape(outputShape);
1711
1712 // this is no-op for identity swizzles, otherwise it replaces both
1713 // the handles and shapes with the swizzled layer output handles and shapes
1714 SwizzleInputs(*data.m_Network, inputHandles, inputShapes, permutationPair.first);
1715
1716 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
1717 armnn::OriginsDescriptor concatDescriptor;
1718
1719 try
1720 {
1721 // The concat descriptor is always created across the only supported concat dimension
1722 // which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
1723 concatDescriptor =
1724 armnn::CreateDescriptorForConcatenation(inputShapes.begin(), inputShapes.end(), concatDim);
1725 }
1726 catch (const armnn::Exception& error)
1727 {
1728 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
1729 }
1730
1731 // Validate the output shape is correct given the input shapes based on the
1732 // only valid concat dimension which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
1733 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
1734 {
1735 return Fail("%s: Error validating the output shape for concat", __func__);
1736 }
1737
1738 std::vector<const armnn::TensorInfo*> inputTensorInfos;
1739 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
1740 [](const LayerInputHandle& h) -> const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
1741
1742 bool isSupported = false;
1743 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1744 IsConcatSupported,
1745 data.m_Backends,
1746 isSupported,
1747 inputTensorInfos,
1748 outputInfo,
1749 concatDescriptor);
1750 if (!isSupported)
1751 {
1752 return false;
1753 }
1754
1755 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
1756 assert(layer != nullptr);
1757 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1758
1759 // Connect inputs to the layer
1760 const int numInputSlots = layer->GetNumInputSlots();
1761 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
1762 for (int i = 0; i < numInputSlots; ++i)
1763 {
1764 // connect the input directly to the merge (concat) layer
1765 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
1766 }
1767
1768 if (needPermute)
1769 {
1770 // Add permutation layer and connect the output to it, the permutation becomes the output layer
1771 armnn::IConnectableLayer& deswizzleLayer = AddPermuteLayer(*data.m_Network,
1772 layer->GetOutputSlot(0),
1773 permutationPair.second);
1774 layer = &deswizzleLayer;
1775 }
1776
1777 if (inputsHaveBeenReshaped)
1778 {
1779 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
1780
1781 // Undo the reshape knowing the amount of dimensions added
1782 if (tensorDimensionsAdded == 1)
1783 {
1784 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[1],
1785 afterConcatInfo.GetShape()[2] }));
1786 }
1787 else if (tensorDimensionsAdded == 2)
1788 {
1789 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[2] }));
1790 }
1791
1792 layer = &AddReshapeLayer(
1793 *data.m_Network,
1794 layer->GetOutputSlot(0),
1795 afterConcatInfo
1796 );
1797 }
1798
1799 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
1800}
1801
1802template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001803 typename HalOperation = typename HalPolicy::Operation,
1804 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001805bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1806{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001807 using HalOperand = typename HalPolicy::Operand;
1808 using HalOperandType = typename HalPolicy::OperandType;
1809
1810 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001811 if (!input.IsValid())
1812 {
1813 return Fail("%s: Operation has invalid inputs", __func__);
1814 }
1815
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001816 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001817 if (!output)
1818 {
1819 return Fail("%s: Could not read output 0", __func__);
1820 }
1821
1822 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001823 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001824
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001825 if (IsDynamicTensor(outputInfo))
1826 {
1827 return Fail("%s: Dynamic output tensors are not supported", __func__);
1828 }
1829
Mike Kellyb5fdf382019-06-11 16:35:25 +01001830 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001831 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
1832 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001833
1834 if (!weightsPin.IsValid() || !biasPin.IsValid())
1835 {
1836 return Fail("%s: Operation has invalid inputs", __func__);
1837 }
1838
1839 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001840 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01001841 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1842
1843 armnn::Convolution2dDescriptor desc;
1844 desc.m_DataLayout = armnn::DataLayout::NHWC;
1845 ActivationFn activation;
1846
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001847 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001848 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001849 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1850 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1851 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1852 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1853 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1854 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001855 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001856 {
1857 return Fail("%s: Operation has invalid inputs", __func__);
1858 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001859 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001860 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001861 {
1862 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001863 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1864 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1865 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01001866 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001867 {
1868 return Fail("%s: Operation has invalid inputs", __func__);
1869 }
1870
1871 const uint32_t kernelX = weights.GetShape()[2];
1872 const uint32_t kernelY = weights.GetShape()[1];
1873 const uint32_t inputX = inputInfo.GetShape()[2];
1874 const uint32_t inputY = inputInfo.GetShape()[1];
1875
1876 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1877 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001878 }
1879 else
1880 {
1881 return Fail("%s: Unsupported number of operation inputs", __func__);
1882 }
1883
1884 desc.m_BiasEnabled = true;
1885 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1886
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001887 bool isSupported = false;
1888 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1889 IsConvolution2dSupported,
1890 data.m_Backends,
1891 isSupported,
1892 inputInfo,
1893 outputInfo,
1894 desc,
1895 weights.GetInfo(),
1896 biases);
1897 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001898 {
1899 return false;
1900 }
1901
1902 armnn::IConnectableLayer* startLayer =
1903 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1904
1905 if (!startLayer)
1906 {
1907 return Fail("%s: AddConvolution2dLayer failed", __func__);
1908 }
1909
1910 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1911
1912 if (!endLayer)
1913 {
1914 return Fail("%s: ProcessActivation failed", __func__);
1915 }
1916
1917 input.Connect(startLayer->GetInputSlot(0));
1918
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001919 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001920}
1921
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001922template<typename HalPolicy,
1923 typename HalOperation = typename HalPolicy::Operation,
1924 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01001925bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
1926{
1927 using HalOperand = typename HalPolicy::Operand;
1928 using HalOperandType = typename HalPolicy::OperandType;
1929
1930 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1931 if (!input.IsValid() )
1932 {
1933 return Fail("%s: Operation has invalid inputs", __func__);
1934 }
1935
1936 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1937 unsigned int rank = inputInfo.GetNumDimensions();
1938 if (rank != 4)
1939 {
1940 return Fail("%s: Only inputs with rank 4 are supported", __func__);
1941 }
1942
1943 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1944 if (!output)
1945 {
1946 return Fail("%s: Could not read output 0", __func__);
1947 }
1948
1949 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1950 if (IsDynamicTensor(outputInfo))
1951 {
1952 return Fail("%s: Dynamic output tensors are not supported", __func__);
1953 }
1954
1955 armnn::DepthToSpaceDescriptor descriptor;
1956
1957 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
1958 if (descriptor.m_BlockSize <= 1)
1959 {
1960 return Fail("%s: Block size must be at least 1 in all dimensions");
1961 }
1962
1963 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
1964 if (Is12Operand(*output))
1965 {
1966 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
1967 }
1968
1969 bool isSupported = false;
1970 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1971 IsDepthToSpaceSupported,
1972 data.m_Backends,
1973 isSupported,
1974 inputInfo,
1975 outputInfo,
1976 descriptor);
1977 if (!isSupported)
1978 {
1979 return false;
1980 }
1981
1982 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
1983 assert(layer != nullptr);
1984 input.Connect(layer->GetInputSlot(0));
1985
1986 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
1987}
1988
1989template<typename HalPolicy,
1990 typename HalOperation = typename HalPolicy::Operation,
1991 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001992bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1993{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001994 using HalOperand = typename HalPolicy::Operand;
1995 using HalOperandType = typename HalPolicy::OperandType;
1996
1997 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001998
1999 if (!input.IsValid())
2000 {
2001 return Fail("%s: Operation has invalid inputs", __func__);
2002 }
2003
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002004 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002005
2006 if (!output)
2007 {
2008 return Fail("%s: Could not read output 0", __func__);
2009 }
2010
2011 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002012 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002013
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002014 if (IsDynamicTensor(outputInfo))
2015 {
2016 return Fail("%s: Dynamic output tensors are not supported", __func__);
2017 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002018
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002019 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002020 // 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 +01002021 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002022
2023 if (weightsOperand == nullptr)
2024 {
2025 return Fail("%s: Operand is invalid", __func__);
2026 }
2027 armnn::DepthwiseConvolution2dDescriptor desc;
2028 desc.m_DataLayout = armnn::DataLayout::NHWC;
2029
Mike Kellyb5fdf382019-06-11 16:35:25 +01002030 // Reinterpret weight data as [ H, W, I, M ]
2031 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2032 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002033 inputInfo.GetShape()[3],
2034 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002035
2036 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2037 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2038
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002039 const ConstTensorPin weightsPin =
2040 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2041 1,
2042 model,
2043 data,
2044 HWIMToMIHW,
2045 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002046
2047 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002048 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002049
2050 if (!weightsPin.IsValid() || !biasPin.IsValid())
2051 {
2052 return Fail("%s: Operation has invalid inputs", __func__);
2053 }
2054
2055 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2056 armnn::ConstTensor bias = biasPin.GetConstTensor();
2057 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2058
2059 ActivationFn activation;
2060
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002061 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002062 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002063 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2064 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2065 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2066 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2067 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2068 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002069 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002070 {
2071 return Fail("%s: Operation has invalid inputs", __func__);
2072 }
2073 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002074 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002075 {
2076 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002077 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2078 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2079 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002080 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002081 {
2082 return Fail("%s: Operation has invalid inputs", __func__);
2083 }
2084
2085 const uint32_t kernelX = weights.GetShape()[3];
2086 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002087 const uint32_t inputX = inputInfo.GetShape()[2];
2088 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002089
2090 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2091 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2092 }
2093 else
2094 {
2095 return Fail("%s: Unsupported number of operation inputs", __func__);
2096 }
2097
2098 desc.m_BiasEnabled = true;
2099 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2100
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002101 bool isSupported = false;
2102 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2103 IsDepthwiseConvolutionSupported,
2104 data.m_Backends,
2105 isSupported,
2106 inputInfo,
2107 outputInfo,
2108 desc,
2109 weights.GetInfo(),
2110 biases);
2111 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002112 {
2113 return false;
2114 }
2115
2116 armnn::IConnectableLayer* startLayer =
2117 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2118 if (!startLayer)
2119 {
2120 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2121 }
2122
2123 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2124 if (!endLayer)
2125 {
2126 return Fail("%s: ProcessActivation failed", __func__);
2127 }
2128
2129 input.Connect(startLayer->GetInputSlot(0));
2130
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002131 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
arovir01b0717b52018-09-05 17:03:25 +01002132}
2133
Mike Kelly3c673942019-07-25 09:26:06 +01002134template<typename HalPolicy,
Mike Kelly46272802019-08-14 17:00:48 +01002135 typename Operation = typename HalPolicy::Operation,
2136 typename Model = typename HalPolicy::Model>
2137bool ConvertDequantize(const Operation& operation, const Model& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002138{
Mike Kelly46272802019-08-14 17:00:48 +01002139 using Operand = typename HalPolicy::Operand;
2140
2141 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2142 if (!input.IsValid())
2143 {
2144 return Fail("%s: Operation has invalid input", __func__);
2145 }
2146
2147 const Operand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2148 if (!outputOperand)
2149 {
2150 return Fail("%s: Operation has invalid outputs", __func__);
2151 }
2152
2153 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2154 if (IsDynamicTensor(outputInfo))
2155 {
2156 return Fail("%s: Dynamic output tensors are not supported", __func__);
2157 }
2158
2159 bool isSupported = false;
2160 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2161 IsDequantizeSupported,
2162 data.m_Backends,
2163 isSupported,
2164 input.GetTensorInfo(),
2165 GetTensorInfoForOperand(*outputOperand));
2166 if (!isSupported)
2167 {
2168 return false;
2169 }
2170
2171 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2172 assert(layer != nullptr);
2173 input.Connect(layer->GetInputSlot(0));
2174
2175 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2176}
2177
2178template<typename HalPolicy,
2179 typename Operation = typename HalPolicy::Operation,
2180 typename Model = typename HalPolicy::Model>
2181bool ConvertDiv(const Operation& operation, const Model& model, ConversionData& data)
2182{
2183 using Operand = typename HalPolicy::Operand;
2184
2185 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2186 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2187
2188 if (!input0.IsValid() || !input1.IsValid())
2189 {
2190 return Fail("%s: Operation has invalid inputs", __func__);
2191 }
2192
2193 // The FuseActivation parameter is always the input index 2
2194 // and it should be optional
2195 ActivationFn activationFunction;
2196 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2197 {
2198 return Fail("%s: Operation has invalid inputs", __func__);
2199 }
2200
2201 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2202 if (!output)
2203 {
2204 return Fail("%s: Could not read output 0", __func__);
2205 }
2206
2207 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2208 if (IsDynamicTensor(outputInfo))
2209 {
2210 return Fail("%s: Dynamic output tensors are not supported", __func__);
2211 }
2212
2213 bool isSupported = false;
2214 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2215 IsDivisionSupported,
2216 data.m_Backends,
2217 isSupported,
2218 input0.GetTensorInfo(),
2219 input1.GetTensorInfo(),
2220 outputInfo);
2221 if (!isSupported)
2222 {
2223 return false;
2224 }
2225
2226 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
2227 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2228
2229 if (endLayer)
2230 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01002231 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2232 if (!isReshapeSupported)
2233 {
2234 return false;
2235 }
2236
Mike Kelly46272802019-08-14 17:00:48 +01002237 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2238 }
2239 return Fail("%s: ProcessActivation failed", __func__);
2240}
2241
2242template<typename HalPolicy,
2243 typename Operation = typename HalPolicy::Operation,
2244 typename Model = typename HalPolicy::Model>
2245bool ConvertFloor(const Operation& operation, const Model& model, ConversionData& data)
2246{
2247 using Operand = typename HalPolicy::Operand;
2248
2249 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2250 if (!input.IsValid())
2251 {
2252 return Fail("%s: Operation has invalid inputs", __func__);
2253 }
2254
2255 const Operand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2256 if (!outputOperand)
2257 {
2258 return Fail("%s: Operation has invalid outputs", __func__);
2259 }
2260
2261 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2262 if (IsDynamicTensor(outputInfo))
2263 {
2264 return Fail("%s: Dynamic output tensors are not supported", __func__);
2265 }
2266
2267 bool isSupported = false;
2268 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2269 IsFloorSupported,
2270 data.m_Backends,
2271 isSupported,
2272 input.GetTensorInfo(),
2273 outputInfo);
2274 if (!isSupported)
2275 {
2276 return false;
2277 }
2278
2279 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2280 assert(layer != nullptr);
2281 input.Connect(layer->GetInputSlot(0));
2282
2283 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2284}
2285
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002286inline bool IsQSymm8(const V1_0::Operand&)
2287{
2288 return false;
2289}
2290
2291#ifdef ARMNN_ANDROID_NN_V1_2
2292
2293inline bool IsQSymm8(const V1_2::Operand& operand)
2294{
2295 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2296}
2297
2298#endif
2299
2300template<typename HalPolicy,
2301 typename Operation = typename HalPolicy::Operation,
2302 typename Model = typename HalPolicy::Model>
Sadik Armaganac23b032019-11-18 17:11:21 +00002303std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, int>
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002304DequantizeIfRequired(size_t operand_index, const Operation& operation, const Model& model, const ConversionData& data)
2305{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002306 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002307
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002308 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armaganac23b032019-11-18 17:11:21 +00002309 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002310 {
Sadik Armaganac23b032019-11-18 17:11:21 +00002311 // Invalid Operand will return with error code '-1'
2312 return { nullptr, 0, armnn::TensorInfo(), -1 };
2313 }
2314
2315 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2316 {
2317 // Weights are already constant
2318 return { nullptr, 0, armnn::TensorInfo(), 0 };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002319 }
2320
2321 const size_t weightsInputIndex = operation.inputs[operand_index];
2322
2323 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2324 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
2325 for (uint32_t operationIdx = 0; operationIdx < model.operations.size(); ++operationIdx)
2326 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002327 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002328 const auto& operationIt = model.operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002329 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2330 {
2331 continue;
2332 }
2333
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002334 size_t outOpIndex = weightsInputIndex + 1;
2335 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002336 {
2337 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002338 }
2339
2340 if (outOpIndex != weightsInputIndex)
2341 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002342 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002343 }
2344
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002345 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002346 BOOST_ASSERT(operand);
2347
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002348 if (!IsQSymm8(*operand))
2349 {
2350 // Only supporting dequantize from QSYMM8 to FLOAT
2351 break;
2352 }
2353
2354 // Allocate a new buffer for the dequantized data and manually dequantize
2355 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2356 if (!startValue)
2357 {
2358 // Failed to get the operand address
2359 break;
2360 }
2361
2362 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2363 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002364 const float quantizationScale = operand->scale;
2365
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002366 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2367 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2368 {
2369 float* dstPtr = dequantizedBuffer.get();
2370 BOOST_ASSERT(dstPtr);
2371 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2372 }
2373
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002374 // Construct tensor info for dequantized ConstTensor
2375 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2376 operand->dimensions.data(),
2377 armnn::DataType::Float32);
2378
Sadik Armaganac23b032019-11-18 17:11:21 +00002379 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float), std::move(tensorInfo), 0 };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002380 }
2381
Sadik Armaganac23b032019-11-18 17:11:21 +00002382 return { nullptr, 0, armnn::TensorInfo() , 0};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002383}
2384
2385template<typename HalPolicy,
2386 typename Operation = typename HalPolicy::Operation,
2387 typename Model = typename HalPolicy::Model>
2388ConstTensorPin DequantizeAndMakeConstTensorPin(const Operation& operation,
2389 const Model& model,
2390 const ConversionData& data,
2391 size_t operandIndex,
2392 bool optional = false)
2393{
2394 auto dequantized = DequantizeIfRequired<HalPolicy, Operation, Model>(operandIndex,operation, model, data);
Sadik Armaganac23b032019-11-18 17:11:21 +00002395 if (std::get<3>(dequantized) == -1)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002396 {
Sadik Armaganac23b032019-11-18 17:11:21 +00002397 // Return it as invalid, tensor with no values is not really an error
2398 return ConstTensorPin();
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002399 }
2400
Sadik Armaganac23b032019-11-18 17:11:21 +00002401 if (std::get<1>(dequantized) == 0)
2402 {
2403 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2404 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
2405
2406 }
2407
2408 return ConstTensorPin(std::get<2>(dequantized), std::get<0>(dequantized).get(),
2409 std::get<1>(dequantized), g_DontPermute);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002410}
2411
2412
Mike Kelly46272802019-08-14 17:00:48 +01002413template<typename HalPolicy,
2414 typename Operation = typename HalPolicy::Operation,
2415 typename Model = typename HalPolicy::Model>
2416bool ConvertFullyConnected(const Operation& operation, const Model& model, ConversionData& data)
2417{
2418 using Operand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002419 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2420 if (!input.IsValid())
2421 {
2422 return Fail("%s: Operation has invalid inputs", __func__);
2423 }
2424
2425 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2426 if (!output)
2427 {
2428 return Fail("%s: Could not read output 0", __func__);
2429 }
2430
2431 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2432 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2433
2434 if (IsDynamicTensor(outputInfo))
2435 {
2436 return Fail("%s: Dynamic output tensors are not supported", __func__);
2437 }
2438
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002439 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
2440 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002441
2442 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01002443 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002444 return Fail("%s: Operation has invalid weights", __func__);
2445 }
2446
2447 if (!biasPin.IsValid())
2448 {
2449 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01002450 }
2451
2452 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2453 armnn::ConstTensor bias = biasPin.GetConstTensor();
2454 armnn::TensorInfo reshapedInfo = inputInfo;
2455
2456 try
2457 {
2458 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002459 }
2460 catch (const std::exception& e)
2461 {
Mike Kelly46272802019-08-14 17:00:48 +01002462 return Fail("%s: %s", __func__, e.what());
2463 }
2464
2465 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
2466 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
2467
2468 ActivationFn activationFunction;
2469 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
2470 {
2471 return Fail("%s: Operation has invalid inputs", __func__);
2472 }
2473
2474 armnn::FullyConnectedDescriptor desc;
2475 desc.m_TransposeWeightMatrix = true;
2476 desc.m_BiasEnabled = true;
2477
2478 bool isSupported = false;
2479 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2480 IsFullyConnectedSupported,
2481 data.m_Backends,
2482 isSupported,
2483 reshapedInfo,
2484 outputInfo,
2485 weights.GetInfo(),
2486 bias.GetInfo(),
2487 desc);
2488 if (!isSupported)
2489 {
2490 return false;
2491 }
2492
2493 armnn::IConnectableLayer* startLayer =
2494 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2495 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2496
2497 if (endLayer != nullptr)
2498 {
2499 if (inputInfo.GetNumDimensions() > 2U)
2500 {
2501 armnn::ReshapeDescriptor reshapeDescriptor;
2502 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
2503
2504 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
2505 assert(reshapeLayer != nullptr);
2506 input.Connect(reshapeLayer->GetInputSlot(0));
2507 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
2508 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
2509 }
2510 else
2511 {
2512 input.Connect(startLayer->GetInputSlot(0));
2513 }
2514
2515 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2516 }
2517 else
2518 {
2519 return Fail("%s: ProcessActivation failed", __func__);
2520 }
2521}
2522
2523template<typename HalPolicy,
2524 typename Operation = typename HalPolicy::Operation,
2525 typename Model = typename HalPolicy::Model>
2526bool ConvertL2Normalization(const Operation& operation, const Model& model, ConversionData& data)
2527{
Mike Kelly999e2092019-08-15 10:46:46 +01002528 if (operation.inputs.size() != 1)
2529 {
2530 return Fail("%s: Optional inputs are not supported", __func__);
2531 }
2532
Mike Kelly46272802019-08-14 17:00:48 +01002533 using Operand = typename HalPolicy::Operand;
2534
2535 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2536 if (!input.IsValid())
2537 {
2538 return Fail("%s: Operation has invalid inputs", __func__);
2539 }
2540
2541 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2542 if (!output)
2543 {
2544 return Fail("%s: Could not read output 0", __func__);
2545 }
2546
2547 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2548 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2549
2550 if (IsDynamicTensor(outputInfo))
2551 {
2552 return Fail("%s: Dynamic output tensors are not supported", __func__);
2553 }
2554 if (outputInfo.GetNumDimensions() != 4u)
2555 {
2556 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
2557 }
2558
2559 armnn::L2NormalizationDescriptor desc;
2560 desc.m_DataLayout = armnn::DataLayout::NHWC;
2561
2562 bool isSupported = false;
2563 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2564 IsL2NormalizationSupported,
2565 data.m_Backends,
2566 isSupported,
2567 inputInfo,
2568 outputInfo,
2569 desc);
2570 if (!isSupported)
2571 {
2572 return false;
2573 }
2574
2575 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
2576 assert(layer != nullptr);
2577 input.Connect(layer->GetInputSlot(0));
2578
2579 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2580}
2581
2582template<typename HalPolicy,
2583 typename Operation = typename HalPolicy::Operation,
2584 typename Model = typename HalPolicy::Model>
2585bool ConvertLocalResponseNormalization(const Operation& operation,
2586 const Model& model,
2587 ConversionData& data)
2588{
Mike Kelly999e2092019-08-15 10:46:46 +01002589 if (operation.inputs.size() != 5)
2590 {
2591 return Fail("%s: Optional inputs are not supported", __func__);
2592 }
2593
Mike Kelly46272802019-08-14 17:00:48 +01002594 using Operand = typename HalPolicy::Operand;
2595 using OperandType = typename HalPolicy::OperandType;
2596
2597 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2598 if (!input.IsValid())
2599 {
2600 return Fail("%s: Operation has invalid inputs", __func__);
2601 }
2602
2603 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2604 if (!output)
2605 {
2606 return Fail("%s: Could not read output 0", __func__);
2607 }
2608
2609 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2610 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2611
2612 if (IsDynamicTensor(outputInfo))
2613 {
2614 return Fail("%s: Dynamic output tensors are not supported", __func__);
2615 }
2616 if (outputInfo.GetNumDimensions() != 4u)
2617 {
2618 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
2619 }
2620
2621 armnn::NormalizationDescriptor descriptor;
2622 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
2623 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
2624 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
2625
2626 if (!input.IsValid() ||
2627 !GetInputScalar<HalPolicy>(operation, 1, OperandType::INT32, descriptor.m_NormSize, model, data) ||
2628 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
2629 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
2630 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
2631 {
2632 return Fail("%s: Operation has invalid inputs", __func__);
2633 }
2634
2635 // ArmNN expects normSize to be the full size of the normalization
2636 // window rather than the radius as in AndroidNN.
2637 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
2638
2639 bool isSupported = false;
2640 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2641 IsNormalizationSupported,
2642 data.m_Backends,
2643 isSupported,
2644 inputInfo,
2645 outputInfo,
2646 descriptor);
2647 if (!isSupported)
2648 {
2649 return false;
2650 }
2651
2652
2653 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
2654 assert(layer != nullptr);
2655 input.Connect(layer->GetInputSlot(0));
2656
2657 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2658}
2659
2660template<typename HalPolicy,
2661 typename Operation = typename HalPolicy::Operation,
2662 typename Model = typename HalPolicy::Model>
2663bool ConvertLogistic(const Operation& operation, const Model& model, ConversionData& data)
2664{
2665 using Operand = typename HalPolicy::Operand;
2666
2667 armnn::ActivationDescriptor desc;
2668 desc.m_Function = armnn::ActivationFunction::Sigmoid;
2669
2670 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
2671}
2672
2673template<typename HalPolicy,
2674 typename Operation = typename HalPolicy::Operation,
2675 typename Model = typename HalPolicy::Model>
2676bool ConvertMean(const Operation& operation, const Model& model, ConversionData& data)
2677{
2678 using Operand = typename HalPolicy::Operand;
2679
2680 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2681 if (!input.IsValid())
2682 {
2683 return Fail("%s: Operation has invalid inputs", __func__);
2684 }
2685
2686 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2687 if (!output)
2688 {
2689 return Fail("%s: Could not read output 0", __func__);
2690 }
2691
2692 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2693 if (IsDynamicTensor(outputInfo))
2694 {
2695 return Fail("%s: Dynamic output tensors are not supported", __func__);
2696 }
2697
2698 const Operand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
2699 if (!axisOperand)
2700 {
2701 return Fail("%s: Could not read input 1", __func__);
2702 }
2703
2704 std::vector<int32_t> axis;
2705 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
2706 {
2707 return Fail("%s: Input 1 has invalid values", __func__);
2708 }
2709
2710 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2711
2712 // Convert the axis to unsigned int and remove duplicates.
2713 unsigned int rank = inputInfo.GetNumDimensions();
2714 std::set<unsigned int> uniqueAxis;
2715 std::transform(axis.begin(), axis.end(),
2716 std::inserter(uniqueAxis, uniqueAxis.begin()),
2717 [rank](int i) -> unsigned int { return (i + rank) % rank; });
2718
2719 // Get the "keep dims" flag.
2720 int32_t keepDims = 0;
2721 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
2722 {
2723 return Fail("%s: Could not read input 2", __func__);
2724 }
2725
2726 armnn::MeanDescriptor descriptor;
2727 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
2728 descriptor.m_KeepDims = keepDims > 0;
2729
2730 bool isSupported = false;
2731 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2732 IsMeanSupported,
2733 data.m_Backends,
2734 isSupported,
2735 inputInfo,
2736 outputInfo,
2737 descriptor);
2738 if (!isSupported)
2739 {
2740 return false;
2741 }
2742
2743 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
2744 assert(layer != nullptr);
2745 input.Connect(layer->GetInputSlot(0));
2746
2747 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2748}
2749
2750template<typename HalPolicy,
2751 typename Operation = typename HalPolicy::Operation,
2752 typename Model = typename HalPolicy::Model>
2753bool ConvertMul(const Operation& operation, const Model& model, ConversionData& data)
2754{
2755 using Operand = typename HalPolicy::Operand;
2756
2757 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2758 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2759
2760 if (!input0.IsValid() || !input1.IsValid())
2761 {
2762 return Fail("%s: Operation has invalid inputs", __func__);
2763 }
2764
2765 // The FuseActivation parameter is always the input index 2
2766 // and it should be optional
2767 ActivationFn activationFunction;
2768 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2769 {
2770 return Fail("%s: Operation has invalid inputs", __func__);
2771 }
2772
2773 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2774
2775 if (outputOperand == nullptr)
2776 {
2777 return false;
2778 }
2779
2780 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2781 if (IsDynamicTensor(outputInfo))
2782 {
2783 return Fail("%s: Dynamic output tensors are not supported", __func__);
2784 }
2785
2786 bool isSupported = false;
2787 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2788 IsMultiplicationSupported,
2789 data.m_Backends,
2790 isSupported,
2791 input0.GetTensorInfo(),
2792 input1.GetTensorInfo(),
2793 outputInfo);
2794 if (!isSupported)
2795 {
2796 return false;
2797 }
2798
2799 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
2800 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2801
2802 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
2803 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
2804
2805 if (endLayer != nullptr)
2806 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01002807 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
2808 if (!isReshapeSupported)
2809 {
2810 return false;
2811 }
2812
Mike Kelly46272802019-08-14 17:00:48 +01002813 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2814 }
2815 else
2816 {
2817 return Fail("%s: ProcessActivation failed", __func__);
2818 }
2819}
2820
2821template<typename HalPolicy,
2822 typename Operation = typename HalPolicy::Operation,
2823 typename Model = typename HalPolicy::Model>
2824bool ConvertPad(Operation& operation, const Model& model, ConversionData& data)
2825{
2826 using Operand = typename HalPolicy::Operand;
2827
Mike Kelly3c673942019-07-25 09:26:06 +01002828 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2829 if (!input.IsValid())
2830 {
2831 return Fail("%s: Operation has invalid inputs", __func__);
2832 }
2833
2834 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2835 unsigned int rank = inputInfo.GetNumDimensions();
2836
2837 armnn::PadDescriptor descriptor;
2838 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
2839 {
2840 return Fail("%s: Could not convert paddings", __func__);
2841 }
2842
2843 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
2844 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
2845 // (QuantizationOffset - QuantizationOffset) * scale = 0.
2846 if (inputInfo.GetDataType() == armnn::DataType::QuantisedAsymm8)
2847 {
2848 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
2849 }
2850
Mike Kelly46272802019-08-14 17:00:48 +01002851 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01002852 if (!output)
2853 {
2854 return Fail("%s: Could not read output", __func__);
2855 }
2856
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002857 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01002858 if (IsDynamicTensor(outputInfo))
2859 {
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002860 return Fail("%s: Dynamic output tensors are not supported", __func__);
Mike Kelly3c673942019-07-25 09:26:06 +01002861 }
2862
2863 bool isSupported = false;
2864 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2865 IsPadSupported,
2866 data.m_Backends,
2867 isSupported,
2868 inputInfo,
2869 outputInfo,
2870 descriptor);
2871 if (!isSupported)
2872 {
2873 return false;
2874 }
2875
2876 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
2877 assert(layer != nullptr);
2878 input.Connect(layer->GetInputSlot(0));
2879 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2880
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002881 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
Mike Kelly3c673942019-07-25 09:26:06 +01002882}
2883
Mike Kelly0a879362019-07-29 16:56:31 +01002884template<typename HalPolicy,
2885 typename Operation = typename HalPolicy::Operation,
Mike Kelly46272802019-08-14 17:00:48 +01002886 typename Model = typename HalPolicy::Model>
2887bool ConvertReshape(const Operation& operation, const Model& model, ConversionData& data)
2888{
2889 using Operand = typename HalPolicy::Operand;
2890
2891 const Operand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
2892 const Operand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
2893 const Operand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
2894
2895 if (inputOperand == nullptr
2896 || requestedShapeOperand == nullptr
2897 || outputOperand == nullptr)
2898 {
2899 return Fail("%s: Operation has invalid inputs", __func__);
2900 }
2901
2902 if (requestedShapeOperand->dimensions.size() != 1)
2903 {
2904 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
2905 __func__, requestedShapeOperand->dimensions.size());
2906 }
2907
2908 std::vector<int32_t> targetDimensions;
2909 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
2910 {
2911 return Fail("%s: Could not read values of input 1", __func__);
2912 }
2913
2914 const Shape inputOperandShape = GetOperandShape(*inputOperand);
2915
2916 Shape requestedShape;
2917 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
2918 // function that resolves these values into a fully specified tensor shape.
2919 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
2920 {
2921 return Fail("%s: Failed to resolve the requested shape", __func__);
2922 }
2923
2924 const Shape outputOperandShape = GetOperandShape(*outputOperand);
2925 if (!SameShape(requestedShape, outputOperandShape))
2926 {
2927 return Fail("%s: Shape of output operand does not match resolved requested shape", __func__);
2928 }
2929
2930 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2931 if (!input.IsValid())
2932 {
2933 return Fail("%s: Could not read input 0", __func__);
2934 }
2935
2936 armnn::ReshapeDescriptor reshapeDescriptor;
2937 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
2938 requestedShape.dimensions.data());
2939
2940 bool isSupported = false;
2941 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2942 IsReshapeSupported,
2943 data.m_Backends,
2944 isSupported,
2945 input.GetTensorInfo(),
2946 reshapeDescriptor);
2947 if (!isSupported)
2948 {
2949 return false;
2950 }
2951
2952 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
2953 assert(layer != nullptr);
2954 input.Connect(layer->GetInputSlot(0));
2955
2956 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2957}
2958
2959template<typename HalPolicy,
2960 typename Operation = typename HalPolicy::Operation,
Mike Kelly0a879362019-07-29 16:56:31 +01002961 typename Model = typename HalPolicy::Model>
2962bool ConvertSub(const Operation& operation, const Model& model, ConversionData& data)
2963{
Mike Kelly46272802019-08-14 17:00:48 +01002964 using Operand = typename HalPolicy::Operand;
2965
Mike Kelly0a879362019-07-29 16:56:31 +01002966 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2967 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2968
2969 if (!input0.IsValid() || !input1.IsValid())
2970 {
2971 return Fail("%s: Operation has invalid inputs", __func__);
2972 }
2973
2974 // The FuseActivation parameter is always the input index 2
2975 // and it should be optional
2976 ActivationFn activationFunction;
2977 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2978 {
2979 return Fail("%s: Operation has invalid inputs", __func__);
2980 }
2981
2982 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2983 if (!output)
2984 {
2985 return Fail("%s: Could not read output 0", __func__);
2986 }
2987
2988 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2989 if (IsDynamicTensor(outputInfo))
2990 {
2991 return Fail("%s: Dynamic output tensors are not supported", __func__);
2992 }
2993
2994 bool isSupported = false;
2995 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2996 IsSubtractionSupported,
2997 data.m_Backends,
2998 isSupported,
2999 input0.GetTensorInfo(),
3000 input1.GetTensorInfo(),
3001 outputInfo);
3002 if (!isSupported)
3003 {
3004 return false;
3005 }
3006
3007 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
3008 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3009
3010 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3011 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3012
3013 if (endLayer)
3014 {
Sadik Armagan64b19b52019-08-19 09:49:58 +01003015 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
3016 if (!isReshapeSupported)
3017 {
3018 return false;
3019 }
Mike Kelly0a879362019-07-29 16:56:31 +01003020 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
3021 }
3022
3023 return Fail("%s: ProcessActivation failed", __func__);
3024}
3025
Finn Williams23b87b32019-07-30 11:44:05 +01003026template<typename HalPolicy,
Mike Kelly46272802019-08-14 17:00:48 +01003027 typename Operation = typename HalPolicy::Operation,
3028 typename Model = typename HalPolicy::Model>
3029bool ConvertSqueeze(const Operation& operation, const Model& model, ConversionData& data)
3030{
3031 using Operand = typename HalPolicy::Operand;
3032
3033 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3034 if (!input.IsValid())
3035 {
3036 return Fail("%s: Operation has invalid inputs", __func__);
3037 }
3038
3039 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3040 unsigned int rank = inputInfo.GetNumDimensions();
3041 if (rank > 4)
3042 {
3043 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3044 }
3045
3046 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3047 if (!output)
3048 {
3049 return Fail("%s: Could not read output 0", __func__);
3050 }
3051
3052 if (IsDynamicTensor(GetTensorInfoForOperand(*output)))
3053 {
3054 return Fail("%s: Dynamic output tensors are not supported", __func__);
3055 }
3056
3057 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3058 // if the operand index is out of bounds.
3059 const Operand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
3060
3061 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3062
3063 std::vector<int32_t> axis;
3064 if (!axisOperand)
3065 {
3066 axis.assign(dimensionSequence,
3067 dimensionSequence + rank);
3068 }
3069 else
3070 {
3071 GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data);
3072 }
3073
3074 std::vector<uint32_t> outputDims;
3075 for (unsigned int i = 0; i < rank; i++)
3076 {
3077 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3078 auto currentDimension = inputInfo.GetShape()[i];
3079 if (skipSqueeze || currentDimension != 1)
3080 {
3081 outputDims.push_back(currentDimension);
3082 }
3083 }
3084
3085 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3086
3087 armnn::TensorInfo outputInfo = inputInfo;
3088 outputInfo.SetShape(outShape);
3089
3090 armnn::ReshapeDescriptor reshapeDesc;
3091 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3092
3093 bool isSupported = false;
3094 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3095 IsReshapeSupported,
3096 data.m_Backends,
3097 isSupported,
3098 inputInfo,
3099 reshapeDesc);
3100 if (!isSupported)
3101 {
3102 return false;
3103 }
3104
3105 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3106 assert(layer != nullptr);
3107 input.Connect(layer->GetInputSlot(0));
3108
3109 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3110}
3111
3112template<typename HalPolicy,
3113 typename Operation = typename HalPolicy::Operation,
3114 typename Model = typename HalPolicy::Model>
3115bool ConvertStridedSlice(const Operation& operation, const Model& model, ConversionData& data)
3116{
3117 using Operand = typename HalPolicy::Operand;
3118
3119 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3120 if (!input.IsValid())
3121 {
3122 return Fail("%s: Operation has invalid inputs", __func__);
3123 }
3124
3125 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3126 unsigned int rank = inputInfo.GetNumDimensions();
3127 if (rank > 4)
3128 {
3129 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3130 }
3131
3132 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3133 if (!output)
3134 {
3135 return Fail("%s: Could not read output 0", __func__);
3136 }
3137
3138 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3139 if (IsDynamicTensor(outputInfo))
3140 {
3141 return Fail("%s: Dynamic output tensors are not supported", __func__);
3142 }
3143
3144 const Operand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3145 const Operand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3146 const Operand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
3147
3148 std::vector<int32_t> beginValues;
3149 std::vector<int32_t> endValues;
3150 std::vector<int32_t> stridesValues;
3151
3152 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
3153 auto ValidateInputOperands = [&] (const Operand& operand, std::vector<int32_t>& operandValues)
3154 {
3155 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3156 {
3157 return false;
3158 }
3159
3160 if (operandValues.size() != rank)
3161 {
3162 return false;
3163 }
3164
3165 return true;
3166 };
3167
3168 if (!ValidateInputOperands(*beginOperand, beginValues)
3169 || !ValidateInputOperands(*endOperand, endValues)
3170 || !ValidateInputOperands(*stridesOperand, stridesValues))
3171 {
3172 return Fail("%s: Operation has invalid input operand", __func__);
3173 }
3174
3175 // Stride cannot have value '0'
3176 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3177 {
3178 return Fail("%s: Stride must be non-zero value.", __func__);
3179 }
3180
3181 armnn::StridedSliceDescriptor descriptor;
3182 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3183 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3184 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3185 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3186
3187 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3188 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3189 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3190 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3191 {
3192 return Fail("%s: Operation has invalid inputs", __func__);
3193 }
3194
3195 bool isSupported = false;
3196 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3197 IsStridedSliceSupported,
3198 data.m_Backends,
3199 isSupported,
3200 inputInfo,
3201 outputInfo,
3202 descriptor);
3203 if (!isSupported)
3204 {
3205 return false;
3206 }
3207
3208 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3209 assert(layer != nullptr);
3210 input.Connect(layer->GetInputSlot(0));
3211
3212 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3213}
3214
3215template<typename HalPolicy,
3216 typename Operation = typename HalPolicy::Operation,
3217 typename Model = typename HalPolicy::Model>
3218bool ConvertTranspose(const Operation& operation, const Model& model, ConversionData& data)
3219{
3220 using Operand = typename HalPolicy::Operand;
3221
3222 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3223 if (!input.IsValid())
3224 {
3225 return Fail("%s: Operation has invalid inputs", __func__);
3226 }
3227
3228 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3229 unsigned int rank = inputInfo.GetNumDimensions();
3230 if (rank > 4)
3231 {
3232 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3233 }
3234
3235 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3236 // if the operand index is out of bounds.
3237 const Operand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
3238
3239 std::vector<int32_t> perm(rank);
3240 if (!permOperand)
3241 {
3242 // NOTE: If perm is not given, it is set to (n-1...0), where n is the rank of the tensor
3243 for (unsigned int i = rank; i > 0; i--)
3244 {
3245 perm[rank - i] = boost::numeric_cast<int> (i - 1);
3246 }
3247 }
3248 else
3249 {
3250 GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data);
3251 }
3252
3253 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3254
3255 auto permutationVector = armnn::PermutationVector(outputDims.data(), outputDims.size());
3256 if (!permutationVector.IsEqual(NHWCToArmNN)
3257 && !permutationVector.IsEqual(ArmNNToNHWC)
3258 && !permutationVector.IsEqual({ 3, 2, 0, 1 }))
3259 {
3260 return Fail("%s: Only [0, 3, 1, 2], [0, 2, 3, 1] and [3, 2, 0, 1] permutations are supported.", __func__);
3261 }
3262
3263 armnn::PermuteDescriptor permuteDesc;
3264 permuteDesc.m_DimMappings = permutationVector;
3265
3266 const Operand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3267 if (!output)
3268 {
3269 return Fail("%s: Could not read output 0", __func__);
3270 }
3271
3272 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3273
3274 bool isSupported = false;
3275 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3276 IsPermuteSupported,
3277 data.m_Backends,
3278 isSupported,
3279 inputInfo,
3280 outputInfo,
3281 permuteDesc);
3282 if (!isSupported)
3283 {
3284 return false;
3285 }
3286
3287 armnn::IConnectableLayer* const layer = data.m_Network->AddPermuteLayer(permuteDesc);
3288 assert(layer != nullptr);
3289 input.Connect(layer->GetInputSlot(0));
3290
3291 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3292}
3293
3294template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003295 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003296 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003297 typename HalModel = typename HalPolicy::Model>
3298bool ConvertBatchToSpaceNd(const HalOperation& operation,
3299 const HalModel& model,
3300 ConversionData& data)
3301{
Finn Williams23b87b32019-07-30 11:44:05 +01003302
3303 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3304 if (!input.IsValid())
3305 {
3306 return Fail("%s: Operation has invalid inputs", __func__);
3307 }
3308
3309 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3310 if (!output)
3311 {
3312 return Fail("%s: Could not read output 0", __func__);
3313 }
3314
3315 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3316 if (IsDynamicTensor(outputInfo))
3317 {
3318 return Fail("%s: Dynamic output tensors are not supported", __func__);
3319 }
3320
3321 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3322 if (!blockOperand)
3323 {
3324 return Fail("%s: Could not read input 1", __func__);
3325 }
3326
3327 // Convert the block operand to int32
3328 std::vector<int32_t> block;
3329 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
3330 {
3331 return Fail("%s: Input 1 has invalid values", __func__);
3332 }
3333
3334 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3335
3336 unsigned int rank = inputInfo.GetNumDimensions();
3337 if (rank != 4)
3338 {
3339 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
3340 }
3341
3342 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
3343 {
3344 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
3345 " greater than or equal to 1", __func__);
3346 }
3347
3348 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
3349 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
3350 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
3351
3352 if (Is12Operand(*output))
3353 {
Finn Williams0e4e4392019-07-31 10:56:27 +01003354 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01003355 }
3356 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
3357 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
3358
3359 bool isSupported = false;
3360 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3361 IsBatchToSpaceNdSupported,
3362 data.m_Backends,
3363 isSupported,
3364 inputInfo,
3365 outputInfo,
3366 batchToSpaceNdDesc);
3367 if (!isSupported)
3368 {
3369 return false;
3370 }
3371
3372 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
3373 assert(layer != nullptr);
3374 input.Connect(layer->GetInputSlot(0));
3375
3376 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3377}
Mike Kelly0a879362019-07-29 16:56:31 +01003378
Finn Williamsd74c5052019-07-30 17:06:00 +01003379template<typename HalPolicy,
3380 typename HalOperation = typename HalPolicy::Operation,
3381 typename HalOperand = typename HalPolicy::Operand,
3382 typename HalModel = typename HalPolicy::Model>
3383bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
3384{
3385 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3386 if (!input.IsValid())
3387 {
3388 return Fail("%s: Operation has invalid inputs", __func__);
3389 }
3390
3391 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3392 unsigned int rank = inputInfo.GetNumDimensions();
3393 unsigned int spatialDim = rank - 2;
3394
3395 if (rank != 4)
3396 {
3397 Fail("%s: Only inputs with rank 4 are supported", __func__);
3398 }
3399
3400 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3401 if (!output)
3402 {
3403 return Fail("%s: Could not read output 0", __func__);
3404 }
3405
3406 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3407 if (IsDynamicTensor(outputInfo))
3408 {
3409 return Fail("%s: Dynamic output tensors are not supported", __func__);
3410 }
3411
3412 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3413 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3414
3415 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
3416 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
3417 {
3418 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
3419 }
3420
3421 std::vector<int32_t> blockShape;
3422 GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data);
3423 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
3424 {
3425 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
3426 }
3427
3428 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
3429 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
3430 {
3431 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
3432 }
3433
3434 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
3435 std::vector<int32_t> paddings;
3436 GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data);
3437 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
3438 {
3439 int paddingBeforeInput = paddings[i];
3440 int paddingAfterInput = paddings[i + 1];
3441 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
3442 {
3443 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
3444 }
3445
3446 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
3447 }
3448
3449 armnn::SpaceToBatchNdDescriptor descriptor;
3450 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3451 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
3452 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
3453
3454 if (Is12Operand(*output))
3455 {
3456 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
3457 }
3458
3459 bool isSupported = false;
3460 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3461 IsSpaceToBatchNdSupported,
3462 data.m_Backends,
3463 isSupported,
3464 inputInfo,
3465 outputInfo,
3466 descriptor);
3467 if (!isSupported)
3468 {
3469 return false;
3470 }
3471
3472 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
3473 assert(layer != nullptr);
3474 input.Connect(layer->GetInputSlot(0));
3475
3476 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3477}
3478
Kevin May407718f2019-09-09 14:46:41 +01003479template<typename HalPolicy,
3480 typename HalOperation = typename HalPolicy::Operation,
3481 typename HalModel = typename HalPolicy::Model>
3482bool ConvertAbs(const HalOperation& operation, const HalModel& model, ConversionData& data)
3483{
3484 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3485
3486 if (!input.IsValid())
3487 {
3488 return Fail("%s: Operation has invalid input", __func__);
3489 }
3490
3491 using HalOperand = typename HalPolicy::Operand;
3492 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3493 if (!output)
3494 {
3495 return Fail("%s: Could not read output 0", __func__);
3496 }
3497
3498 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3499 if (IsDynamicTensor(outputInfo))
3500 {
3501 return Fail("%s: Dynamic output tensors are not supported", __func__);
3502 }
3503
3504 bool isSupported = false;
3505 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3506 IsAbsSupported,
3507 data.m_Backends,
3508 isSupported,
3509 input.GetTensorInfo(),
3510 outputInfo);
3511
3512 if (!isSupported)
3513 {
3514 return false;
3515 }
3516
3517 armnn::IConnectableLayer* const layer = data.m_Network->AddAbsLayer();
3518 assert(layer != nullptr);
3519 input.Connect(layer->GetInputSlot(0));
3520
3521 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3522}
3523
3524
saoste01b8471482018-10-10 09:44:51 +01003525} // namespace armnn_driver