blob: 694e1b2010ee327f27262299b67aabfa91f6a107 [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
Sadik Armagan2050c232019-07-23 16:59:58 +01008#include "OutputShapeUtils.hpp"
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01009#include "Utils.hpp"
10
arovir01b0717b52018-09-05 17:03:25 +010011#include <armnn/ArmNN.hpp>
Ferran Balaguerd30093c2019-07-09 17:04:47 +010012#include <armnn/ILayerSupport.hpp>
13#include <armnn/BackendHelper.hpp>
arovir01b0717b52018-09-05 17:03:25 +010014
Mike Kellyb5fdf382019-06-11 16:35:25 +010015#include "armnn/src/armnnUtils/DataLayoutIndexed.hpp"
arovir01b0717b52018-09-05 17:03:25 +010016#include "armnn/src/armnnUtils/Permute.hpp"
arovir01b0717b52018-09-05 17:03:25 +010017
18#include <ActivationFunctor.h>
19#include <CpuExecutor.h>
20#include <OperationsUtils.h>
21
22#include <boost/assert.hpp>
23#include <boost/core/ignore_unused.hpp>
Aron Virginas-Tar0e7ab542019-04-10 15:02:31 +010024#include <boost/numeric/conversion/cast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010025#include <boost/test/tools/floating_point_comparison.hpp>
26
27#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010028#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010029
30namespace armnn_driver
31{
32
33///
34/// Helper classes
35///
36
37struct ConversionData
38{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010039 ConversionData(const std::vector<armnn::BackendId>& backends)
40 : m_Backends(backends)
41 , m_Network(nullptr, nullptr)
arovir01b0717b52018-09-05 17:03:25 +010042 {}
43
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010044 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010045 armnn::INetworkPtr m_Network;
46 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
47 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
48};
49
50class LayerInputHandle
51{
52public:
53 LayerInputHandle();
54 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
55
56 bool IsValid() const;
57
58 void Connect(armnn::IInputSlot& inputSlot);
59
60 const armnn::TensorInfo& GetTensorInfo() const;
61
62private:
63 armnn::IOutputSlot* m_OutputSlot;
64 bool m_Valid;
65 armnn::TensorInfo m_TensorInfo;
66};
67
68class ConstTensorPin
69{
70public:
71 // Creates an invalid tensor pin (can be used to signal errors)
72 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
73 ConstTensorPin(bool optional = false);
74
75 // @param tensorInfo TensorInfo associated with the tensor.
76 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
77 // the model being converted.
78 // @param numBytes Number of bytes for the tensor data.
79 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
80 const armnn::PermutationVector& mappings);
81
82 ConstTensorPin(const ConstTensorPin& other) = delete;
83 ConstTensorPin(ConstTensorPin&& other) = default;
84
85 bool IsValid() const;
86 bool IsOptional() const;
87
88 const armnn::ConstTensor& GetConstTensor() const;
89 const armnn::ConstTensor* GetConstTensorPtr() const;
90
91private:
92 armnn::ConstTensor m_ConstTensor;
93
94 // Owned memory for swizzled tensor data, only required if the tensor needed
95 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
96 // the pools associated with the model being converted.
97 std::vector<uint8_t> m_SwizzledTensorData;
98
99 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
100 bool m_Optional;
101};
102
103} // namespace armnn_driver
104
105///
106/// Utility functions
107///
108
109namespace
110{
111
112using namespace armnn_driver;
113using namespace android::nn;
114
115// Convenience function to log the reason for failing to convert a model.
116// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
117template<class... Args>
118static bool Fail(const char* formatStr, Args&&... args)
119{
120 ALOGD(formatStr, std::forward<Args>(args)...);
121 return false;
122}
123
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100124// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
125// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
126#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
127 std::string reasonIfUnsupported; \
128 try { \
129 for (auto&& backendId : backends) \
130 { \
131 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
132 if (layerSupportObject) \
133 { \
134 supported = \
135 layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
136 if (supported) \
137 { \
138 break; \
139 } \
140 else \
141 { \
142 if (reasonIfUnsupported.size() > 0) \
143 { \
144 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
145 } \
146 else \
147 { \
148 ALOGD("%s: not supported by armnn", funcName); \
149 } \
150 } \
151 } \
152 else \
153 { \
154 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
155 } \
156 } \
157 if (!supported) \
158 { \
159 ALOGD("%s: not supported by any specified backend", funcName); \
160 } \
161 } catch (const armnn::InvalidArgumentException &e) { \
162 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
arovir01b0717b52018-09-05 17:03:25 +0100163 }
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100164
Mike Kellyb5fdf382019-06-11 16:35:25 +0100165template<typename Operand>
166armnn::TensorShape GetTensorShapeForOperand(const Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100167{
168 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
169}
170
Matthew Bentham912b3622019-05-03 15:49:14 +0100171inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100172{
Matthew Bentham912b3622019-05-03 15:49:14 +0100173 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
174 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
175 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100176}
177
Mike Kellyb5fdf382019-06-11 16:35:25 +0100178#ifdef ARMNN_ANDROID_NN_V1_2
179
180inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
181{
182 return type == V1_2::OperandType::BOOL ||
183 type == V1_2::OperandType::TENSOR_FLOAT16 ||
184 type == V1_2::OperandType::TENSOR_FLOAT32 ||
185 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
186 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
187 type == V1_2::OperandType::TENSOR_INT32;
188}
189
190#endif
191
192inline bool IsBool(V1_0::Operand)
193{
194 return false;
195}
196
Sadik Armagan61113162019-07-25 09:09:40 +0100197inline bool Is12Operand(V1_0::Operand)
198{
199 return false;
200}
201
Mike Kellyb5fdf382019-06-11 16:35:25 +0100202#ifdef ARMNN_ANDROID_NN_V1_2
203
204inline bool IsBool(V1_2::Operand operand)
205{
206 return operand.type == V1_2::OperandType::BOOL;
207}
208
Sadik Armagan61113162019-07-25 09:09:40 +0100209/// Checks if a operand is 1_2 Operand
210inline bool Is12Operand(V1_2::Operand)
211{
212 return true;
213}
214
Mike Kellyb5fdf382019-06-11 16:35:25 +0100215#endif
216
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100217template<typename LayerHandleType>
218armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network, LayerHandleType& inputLayer,
219 armnn::TensorInfo reshapeInfo)
220{
221 armnn::ReshapeDescriptor reshapeDescriptor;
222 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
223
224 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
225 BOOST_ASSERT(reshapeLayer != nullptr);
226
227 // Attach the input layer to the reshape layer
228 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
229 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
230
231 return *reshapeLayer;
232}
233
234void BroadcastTensor(LayerInputHandle& input0, LayerInputHandle& input1,
235 armnn::IConnectableLayer* startLayer, armnn::INetwork& network)
arovir01b0717b52018-09-05 17:03:25 +0100236{
237 BOOST_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100238
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100239 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
240 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
241
242 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
243 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
244
245 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100246 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100247 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
248 input0.Connect(startLayer->GetInputSlot(0));
249 input1.Connect(startLayer->GetInputSlot(1));
250
251 return;
252 }
253
254 // Since the number of dimensions do not match then we need to add degenerate dimensions
255 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
256
257 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
258 unsigned int sizeDifference = std::abs(boost::numeric_cast<int>(inputDimensions0) -
259 boost::numeric_cast<int>(inputDimensions1));
260
261 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
262 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
263 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
264
265 const armnn::TensorShape& smallShape = smallInfo.GetShape();
266 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
267 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
268 {
269 reshapedDimensions[i] = smallShape[i - sizeDifference];
270 }
271
272 armnn::TensorInfo reshapedInfo = smallInfo;
273 reshapedInfo.SetShape(armnn::TensorShape{ boost::numeric_cast<unsigned int>(reshapedDimensions.size()),
274 reshapedDimensions.data() });
275 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(network, smallInputHandle, reshapedInfo);
276
277 if (input0IsSmaller)
278 {
279 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
280 //
281 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100282 // | |
283 // Reshape |
284 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100285 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100286
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100287 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
288 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100289 }
290 else
291 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100292 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
293 //
294 // Input0 Input1
295 // | |
296 // | Reshape
297 // \ /
298 // StartLayer
299
arovir01b0717b52018-09-05 17:03:25 +0100300 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100301 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100302 }
303}
304
305void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
306 android::nn::PaddingScheme scheme)
307{
308 int32_t padHead;
309 int32_t padTail;
310 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
311 outPadHead = boost::numeric_cast<uint32_t>(padHead);
312 outPadTail = boost::numeric_cast<uint32_t>(padTail);
313}
314
Mike Kelly86b36d42019-07-12 16:39:33 +0100315#ifdef ARMNN_ANDROID_NN_V1_2
316
317void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
318 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
319{
320 int32_t padHead;
321 int32_t padTail;
322 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
323 outPadHead = boost::numeric_cast<uint32_t>(padHead);
324 outPadTail = boost::numeric_cast<uint32_t>(padTail);
325}
326
327#endif
328
Matthew Bentham912b3622019-05-03 15:49:14 +0100329Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100330{
331 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100332 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100333 shape.dimensions = operand.dimensions;
334 shape.scale = operand.scale;
335 shape.offset = operand.zeroPoint;
336 return shape;
337}
338
339// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
340// what AndroidNN requires. However for some of the AndroidNN tests the values don't exactly match so
341// we accept some tolerance. We don't want to ArmNN itself to accept these inconsistencies as it is up to the user
342// (us, in this case) to ensure they match.
343void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
344 const armnn::TensorInfo& weightInfo, const armnn::TensorInfo& inputInfo)
345{
346 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
347 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
348 {
349 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
350 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
351 {
352 ALOGW("Bias quantization scale has been modified to match input*weights");
353 biasInfo.SetQuantizationScale(expectedBiasScale);
354 }
355 }
356}
357
358// 4D Tensor Permutations
359const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
360const armnn::PermutationVector NHWCToArmNN({ 0U, 2U, 3U, 1U });
361const armnn::PermutationVector ArmNNToNHWC({ 0U, 3U, 1U, 2U });
362const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
363
364// 3D Permutation Vectors
365const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
366const armnn::PermutationVector RotateTensorLeft({ 2U, 0U, 1U });
367const armnn::PermutationVector RotateTensorRight({ 1U, 2U, 0U });
368
369template<typename OSlot>
370armnn::IConnectableLayer& AddPermuteLayer(armnn::INetwork& network, OSlot& input,
371 const armnn::PermutationVector& mappings)
372{
373 // Add swizzle layer
374 armnn::IConnectableLayer* const layer = network.AddPermuteLayer(mappings);
375
376 BOOST_ASSERT(layer != nullptr);
377
378 // Connect input to swizzle layer
379 input.Connect(layer->GetInputSlot(0));
380
381 // Setup swizzled output
382 const armnn::TensorInfo outInfo = armnnUtils::Permuted(input.GetTensorInfo(), mappings);
383 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
384
385 return *layer;
386}
387
388void SwizzleIn(armnn::INetwork& network, LayerInputHandle& input, armnn::IConnectableLayer& layer, unsigned int index)
389{
390 // Add swizzle layer
391 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, input, NHWCToArmNN);
392 // Connect swizzled input to layer
393 swizzleLayer.GetOutputSlot(0).Connect(layer.GetInputSlot(index));
394}
395
396armnn::IConnectableLayer& DeswizzleOut(armnn::INetwork& network, armnn::IConnectableLayer& layer, unsigned int index)
397{
398 // Add deswizzle layer
399 armnn::IConnectableLayer& deswizzleLayer = AddPermuteLayer(network, layer.GetOutputSlot(index), ArmNNToNHWC);
400 return deswizzleLayer;
401}
402
403// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
404armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network,
405 LayerInputHandle& input,
406 armnn::IConnectableLayer& firstLayer,
407 armnn::IConnectableLayer& lastLayer)
408{
409 SwizzleIn(network, input, firstLayer, 0);
410 return DeswizzleOut(network, lastLayer, 0);
411}
412
413// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
414armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network, LayerInputHandle& input,
415 armnn::IConnectableLayer& layer)
416{
417 return SwizzleInDeswizzleOut(network, input, layer, layer);
418}
419
420bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
421 const armnn::TensorShape & outputShape,
422 uint32_t concatDim)
423{
424 // Validate the output shape is correct given the input shapes (which have just been validated)
425 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
426 if (outputShape.GetNumDimensions() != numDimensions)
427 {
428 return Fail("%s: Output shape has wrong number of dimensions", __func__);
429 }
430
431 unsigned int outputSizeAlongConcatenatedDimension = 0;
432 for (unsigned int i = 0; i < inputShapes.size(); i++)
433 {
434 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
435 }
436
437 for (unsigned int i = 0; i < numDimensions; ++i)
438 {
439 if (i == concatDim)
440 {
441 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
442 {
443 return Fail(
444 "%s: Invalid output shape for dimension %d (%d != %d)",
445 __func__,
446 i,
447 outputShape[i],
448 outputSizeAlongConcatenatedDimension);
449 }
450 }
451 else
452 {
453 if (outputShape[i] != inputShapes[0][i])
454 {
455 return Fail("%s: Invalid output shape", __func__);
456 }
457 }
458 }
459
460 return true;
461}
462
463bool RequiresReshape(armnn::TensorShape & inputShape)
464{
465 return inputShape.GetNumDimensions() < 3;
466}
467
arovir01b0717b52018-09-05 17:03:25 +0100468void SwizzleInputs(armnn::INetwork& network,
469 std::vector<LayerInputHandle>& inputs,
470 std::vector<armnn::TensorShape>& inputShapes,
471 const armnn::PermutationVector& mapping)
472{
473 if (!mapping.IsEqual(IdentityPermutation4D))
474 {
475 size_t nInputs = inputs.size();
476 for (size_t i=0; i<nInputs; ++i)
477 {
478 // add swizzle layer
479 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, inputs[i], mapping);
480 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
481 auto& outputInfo = outputSlot.GetTensorInfo();
482 // replace inputs with the swizzled ones
483 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
484 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
485 }
486 }
487}
488
narpra01f176d5a2018-11-18 20:17:48 +0000489bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
490 int32_t & concatDimension,
491 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100492{
narpra01f176d5a2018-11-18 20:17:48 +0000493 bool needPermute = false;
arovir01b0717b52018-09-05 17:03:25 +0100494 BOOST_ASSERT(numberOfDimensions >= 3);
495
496 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000497 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
498 // or along dimension 0 or 2 for a 3-D tensor.
499 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100500 {
narpra01f176d5a2018-11-18 20:17:48 +0000501 concatDimension = 1;
502 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
503 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100504 }
narpra01f176d5a2018-11-18 20:17:48 +0000505 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100506 {
narpra01f176d5a2018-11-18 20:17:48 +0000507 concatDimension = 0;
508 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
509 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100510 }
narpra01f176d5a2018-11-18 20:17:48 +0000511 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100512}
513
514} // anonymous namespace
515
516namespace armnn_driver
517{
518
519//// Creates an ArmNN activation layer and connects it to the given layer, if the
520//// passed in AndroidNN activation function requires so.
521//// @return The end layer of the sequence of layers built for the given AndroidNN
522//// activation function or nullptr if an error occurred (e.g. unsupported activation).
523//// Note that the end layer matches the input layer if no activation is required
524//// (the sequence of layers has length 1).
525armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
526 ActivationFn activation,
527 armnn::IConnectableLayer* prevLayer,
528 ConversionData& data);
529
530} // namespace armnn_driver
531
532///
533/// Utility templates
534///
535
536namespace armnn_driver
537{
538
539using namespace android::nn;
540
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100541template<typename HalPolicy,
542 typename HalOperand = typename HalPolicy::Operand,
543 typename HalOperation = typename HalPolicy::Operation,
544 typename HalModel = typename HalPolicy::Model>
545const HalOperand* GetInputOperand(const HalOperation& operation,
546 uint32_t inputIndex,
547 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100548 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100549{
550 if (inputIndex >= operation.inputs.size())
551 {
saoste01b8471482018-10-10 09:44:51 +0100552 if (failOnIndexOutOfBounds)
553 {
554 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
555 }
arovir01b0717b52018-09-05 17:03:25 +0100556 return nullptr;
557 }
558
559 BOOST_ASSERT(operation.inputs[inputIndex] < model.operands.size()); // Model should have been validated beforehand
560 return &model.operands[operation.inputs[inputIndex]];
561}
562
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100563template<typename HalPolicy,
564 typename HalOperand = typename HalPolicy::Operand,
565 typename HalOperation = typename HalPolicy::Operation,
566 typename HalModel = typename HalPolicy::Model>
567const HalOperand* GetOutputOperand(const HalOperation& operation,
568 uint32_t outputIndex,
569 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100570{
571 if (outputIndex >= operation.outputs.size())
572 {
573 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
574 return nullptr;
575 }
576
577 // Model should have been validated beforehand
578 BOOST_ASSERT(operation.outputs[outputIndex] < model.operands.size());
579
580 return &model.operands[operation.outputs[outputIndex]];
581}
582
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100583template<typename HalPolicy,
584 typename HalOperand = typename HalPolicy::Operand,
585 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100586const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100587 const HalModel& model,
588 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000589 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100590{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100591 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100592
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100593 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100594 switch (operand.lifetime)
595 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100596 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100597 {
598 // Constant found in model.operandValues
599 valueStart = &model.operandValues[operand.location.offset];
600 break;
601 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100602 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100603 {
604 // Constant specified via a Memory object
605 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
606 break;
607 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100608 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000609 {
610 // An optional input tensor with no values is not an error so should not register as a fail
611 if (optional)
612 {
613 valueStart = nullptr;
614 break;
615 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100616 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000617 }
arovir01b0717b52018-09-05 17:03:25 +0100618 default:
619 {
620 // Unsupported/invalid (e.g. can't get value of an input to the model)
621 Fail("%s: unsupported/invalid operand lifetime: %s",
622 __func__, toString(operand.lifetime).c_str());
623 valueStart = nullptr;
624 }
625 }
626
627 return valueStart;
628}
629
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100630template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100631 typename HalOperation = typename HalPolicy::Operation,
632 typename HalModel = typename HalPolicy::Model,
633 typename HalOperandType = typename HalPolicy::OperandType>
634bool GetOperandType(const HalOperation& operation,
635 uint32_t inputIndex,
636 const HalModel& model,
637 HalOperandType& type)
638{
639 using HalOperand = typename HalPolicy::Operand;
640
641 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
642 if (!operand)
643 {
644 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
645 }
646
647 type = operand->type;
648 return true;
649}
650
651template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100652 typename HalOperand = typename HalPolicy::Operand,
653 typename HalModel = typename HalPolicy::Model>
654ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
655 const HalModel& model,
656 const ConversionData& data,
657 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
658 const armnn::TensorShape* overrideTensorShape = nullptr,
659 bool optional = false)
660{
661 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
662
663 if (!IsOperandTypeSupportedForTensors(operand.type))
664 {
665 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
666 return ConstTensorPin();
667 }
668
669 if (!optional &&
670 operand.lifetime != HalOperandLifeTime::CONSTANT_COPY &&
671 operand.lifetime != HalOperandLifeTime::CONSTANT_REFERENCE &&
672 operand.lifetime != HalOperandLifeTime::NO_VALUE)
673 {
674 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
675 return ConstTensorPin();
676 }
677
678 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
679 if (!valueStart)
680 {
681 if (optional)
682 {
683 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
684 return ConstTensorPin(true);
685 }
686 // mandatory tensor with no values
687 Fail("%s: failed to get operand address", __func__);
688 return ConstTensorPin();
689 }
690
691 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
692 if (overrideTensorShape != nullptr)
693 {
694 tensorInfo.SetShape(*overrideTensorShape);
695 }
696 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
697}
698
699template<typename HalPolicy,
700 typename HalOperation = typename HalPolicy::Operation,
701 typename HalModel = typename HalPolicy::Model>
702ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
703 uint32_t inputIndex,
704 const HalModel& model,
705 const ConversionData& data,
706 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
707 const armnn::TensorShape* overrideTensorShape = nullptr,
708 bool optional = false)
709{
710 using HalOperand = typename HalPolicy::Operand;
711
712 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
713 if (!operand)
714 {
715 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
716 return ConstTensorPin();
717 }
718 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
719 model,
720 data,
721 dimensionMappings,
722 overrideTensorShape,
723 optional);
724}
725
726template<typename HalPolicy,
727 typename OutputType,
728 typename HalOperandType = typename HalPolicy::OperandType,
729 typename HalOperation = typename HalPolicy::Operation,
730 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100731bool GetInputScalar(const HalOperation& operation,
732 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100733 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100734 OutputType& outValue,
735 const HalModel& model,
736 const ConversionData& data)
737{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100738 using HalOperand = typename HalPolicy::Operand;
739
740 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +0100741 if (!operand)
742 {
743 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
744 }
745
746 if (operand->type != type)
747 {
748 return Fail("%s: unexpected operand type: %s (should be %s)",
749 __func__, toString(operand->type).c_str(), toString(type).c_str());
750 }
751
752 if (operand->location.length != sizeof(OutputType))
753 {
754 return Fail("%s: incorrect operand location length: %i (should be %i)",
755 __func__, operand->location.length, sizeof(OutputType));
756 }
757
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100758 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100759 if (!valueAddress)
760 {
761 return Fail("%s: failed to get address for operand", __func__);
762 }
763
764 outValue = *(static_cast<const OutputType*>(valueAddress));
765 return true;
766}
767
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100768template<typename HalPolicy,
769 typename HalOperation = typename HalPolicy::Operation,
770 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100771bool GetInputInt32(const HalOperation& operation,
772 uint32_t inputIndex,
773 int32_t& outValue,
774 const HalModel& model,
775 const ConversionData& data)
776{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100777 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100778}
779
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100780template<typename HalPolicy,
781 typename HalOperation = typename HalPolicy::Operation,
782 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100783bool GetInputFloat32(const HalOperation& operation,
784 uint32_t inputIndex,
785 float& outValue,
786 const HalModel& model,
787 const ConversionData& data)
788{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100789 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100790}
791
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100792template<typename HalPolicy,
793 typename HalOperation = typename HalPolicy::Operation,
794 typename HalOperandType = typename HalPolicy::OperandType,
795 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100796bool GetInputActivationFunctionImpl(const HalOperation& operation,
797 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100798 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100799 ActivationFn& outActivationFunction,
800 const HalModel& model,
801 const ConversionData& data)
802{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100803 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100804 {
805 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
806 __func__,
807 toString(type).c_str(),
808 toString(OperandType::INT32).c_str(),
809 toString(OperandType::TENSOR_INT32).c_str());
810 }
811
812 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100813 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100814 {
815 return Fail("%s: failed to get activation input value", __func__);
816 }
817 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
818 return true;
819}
820
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100821template<typename HalPolicy,
822 typename HalOperation = typename HalPolicy::Operation,
823 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100824bool GetInputActivationFunction(const HalOperation& operation,
825 uint32_t inputIndex,
826 ActivationFn& outActivationFunction,
827 const HalModel& model,
828 const ConversionData& data)
829{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100830 return GetInputActivationFunctionImpl<HalPolicy>(operation,
831 inputIndex,
832 HalPolicy::OperandType::INT32,
833 outActivationFunction,
834 model,
835 data);
arovir01b0717b52018-09-05 17:03:25 +0100836}
837
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100838template<typename HalPolicy,
839 typename HalOperation = typename HalPolicy::Operation,
840 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100841bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
842 uint32_t inputIndex,
843 ActivationFn& outActivationFunction,
844 const HalModel& model,
845 const ConversionData& data)
846{
847 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100848 return GetInputActivationFunctionImpl<HalPolicy>(operation,
849 inputIndex,
850 HalPolicy::OperandType::INT32,
851 outActivationFunction,
852 model,
853 data);
arovir01b0717b52018-09-05 17:03:25 +0100854}
855
856
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100857template<typename HalPolicy,
858 typename HalOperation = typename HalPolicy::Operation,
859 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100860bool GetOptionalInputActivation(const HalOperation& operation,
861 uint32_t inputIndex,
862 ActivationFn& activationFunction,
863 const HalModel& model,
864 const ConversionData& data)
865{
866 if (operation.inputs.size() <= inputIndex)
867 {
868 activationFunction = ActivationFn::kActivationNone;
869 }
870 else
871 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100872 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100873 {
874 return Fail("%s: Operation has invalid inputs", __func__);
875 }
876 }
877 return true;
878}
879
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100880template<typename HalPolicy,
881 typename ConvolutionDescriptor,
882 typename HalOperation = typename HalPolicy::Operation,
883 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +0100884bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
885 uint32_t dilationXIndex,
886 ConvolutionDescriptor& descriptor,
887 const HalModel& model,
888 const ConversionData& data)
889{
890 bool success = true;
891 if (operation.inputs.size() >= dilationXIndex + 2)
892 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100893 success &= GetInputScalar<HalPolicy>(operation,
894 dilationXIndex,
895 HalPolicy::OperandType::INT32,
896 descriptor.m_DilationX,
897 model,
898 data);
899 success &= GetInputScalar<HalPolicy>(operation,
900 dilationXIndex + 1,
901 HalPolicy::OperandType::INT32,
902 descriptor.m_DilationY,
903 model,
904 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +0100905 }
906
907 return success;
908}
909
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100910template<typename HalPolicy,
911 typename HalOperand = typename HalPolicy::Operand,
912 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100913bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +0100914 std::vector<int32_t>& outValues,
915 const HalModel& model,
916 const ConversionData& data)
917{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100918 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100919 {
920 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
921 }
922
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100923 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100924 if (!startAddress)
925 {
926 return Fail("%s: failed to get operand address", __func__, operand.type);
927 }
928
929 // Check number of bytes is sensible
930 const uint32_t numBytes = operand.location.length;
931 if (numBytes % sizeof(int32_t) != 0)
932 {
933 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
934 __func__, numBytes, sizeof(int32_t));
935 }
936
937 outValues.resize(numBytes / sizeof(int32_t));
938 memcpy(outValues.data(), startAddress, numBytes);
939 return true;
940}
941
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100942template<typename HalPolicy,
943 typename HalOperation = typename HalPolicy::Operation,
944 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100945bool GetInputPaddingScheme(const HalOperation& operation,
946 uint32_t inputIndex,
947 PaddingScheme& outPaddingScheme,
948 const HalModel& model,
949 const ConversionData& data)
950{
951 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100952 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100953 {
954 return Fail("%s: failed to get padding scheme input value", __func__);
955 }
956
957 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
958 return true;
959}
960
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100961template<typename HalPolicy,
962 typename HalOperation = typename HalPolicy::Operation,
963 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100964LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
965 uint32_t inputIndex,
966 const HalModel& model,
967 ConversionData& data)
968{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100969 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +0100970 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100971 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
972
973 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +0100974 if (!operand)
975 {
976 Fail("%s: failed to get input operand %i", __func__, inputIndex);
977 return LayerInputHandle();
978 }
979
980 if (!IsOperandTypeSupportedForTensors(operand->type))
981 {
982 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
983 return LayerInputHandle();
984 }
985
Sadik Armagan44bcc022019-06-18 17:21:36 +0100986 try
arovir01b0717b52018-09-05 17:03:25 +0100987 {
Sadik Armagan44bcc022019-06-18 17:21:36 +0100988 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +0100989 if (IsDynamicTensor(operandTensorInfo))
990 {
991 Fail("%s: dynamic input tensors are not supported", __func__);
992 return LayerInputHandle();
993 }
arovir01b0717b52018-09-05 17:03:25 +0100994
Sadik Armagan44bcc022019-06-18 17:21:36 +0100995 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +0100996 {
Sadik Armagan44bcc022019-06-18 17:21:36 +0100997 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +0100998 {
999 // NOTE: We must check whether we can support the input tensor on at least one
1000 // of the provided backends; otherwise we cannot convert the operation
1001 bool isInputSupported = false;
1002 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1003 IsInputSupported,
1004 data.m_Backends,
1005 isInputSupported,
1006 operandTensorInfo);
1007
1008 if (!isInputSupported)
1009 {
1010 Fail("%s: unsupported input tensor", __func__);
1011 return LayerInputHandle();
1012 }
1013
1014 BOOST_FALLTHROUGH; // intentional fallthrough
1015 }
1016 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001017 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001018 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001019 // The tensor is either an operand internal to the model, or a model input.
1020 // It can be associated with an ArmNN output slot for an existing layer.
1021
1022 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1023 const uint32_t operandIndex = operation.inputs[inputIndex];
1024 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001025 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001026 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001027 case HalOperandLifeTime::CONSTANT_REFERENCE:
1028 {
1029 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1030 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1031 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001032 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001033 bool isSupported = false;
1034 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1035 IsConstantSupported,
1036 data.m_Backends,
1037 isSupported,
1038 tensorPin.GetConstTensor().GetInfo());
1039 if (isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001040 {
1041 return LayerInputHandle();
1042 }
1043
1044 armnn::IConnectableLayer* constantLayer =
1045 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1046 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1047 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1048
1049 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1050 }
1051 else
1052 {
1053 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001054 return LayerInputHandle();
1055 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001056 break;
arovir01b0717b52018-09-05 17:03:25 +01001057 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001058 default:
arovir01b0717b52018-09-05 17:03:25 +01001059 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001060 // Unsupported lifetime for an input tensor
1061 Fail("%s: unsupported lifetime for input tensor: %s",
1062 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001063 return LayerInputHandle();
1064 }
arovir01b0717b52018-09-05 17:03:25 +01001065 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001066 }
1067 catch (UnsupportedOperand<HalOperandType>& e)
1068 {
1069 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1070 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001071 }
1072}
1073
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001074template<typename HalPolicy,
1075 typename HalOperation = typename HalPolicy::Operation,
1076 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001077bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1078 uint32_t operationOutputIndex,
1079 armnn::IConnectableLayer& layer,
1080 uint32_t layerOutputIndex,
1081 const HalModel& model,
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001082 ConversionData& data,
1083 const armnn::Optional<armnn::TensorInfo>& outputInfo = armnn::EmptyOptional())
Mike Kellyb5fdf382019-06-11 16:35:25 +01001084{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001085 using HalOperand = typename HalPolicy::Operand;
1086
1087 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001088 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1089 {
1090 return false;
1091 }
1092
1093 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
1094
1095 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1096 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1097
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001098 if (outputInfo.has_value())
1099 {
1100 outputSlot.SetTensorInfo(outputInfo.value());
1101 ALOGD("Output info overwritten");
1102 }
1103 else
1104 {
1105 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1106 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001107
1108 return true;
1109}
1110
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001111template<typename HalPolicy,
1112 typename HalOperation = typename HalPolicy::Operation,
1113 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001114armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1115 uint32_t inputIndex,
1116 const HalModel& model,
1117 ConversionData& data)
1118{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001119 using HalOperand = typename HalPolicy::Operand;
1120
1121 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001122 if (!operand)
1123 {
1124 return armnn::DataLayout::NHWC;
1125 }
1126
1127 if (!IsBool(*operand))
1128 {
1129 return armnn::DataLayout::NHWC;
1130 }
1131
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001132 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001133 if (!valueAddress)
1134 {
1135 return armnn::DataLayout::NHWC;
1136 }
1137
1138 if (*(static_cast<const bool*>(valueAddress)))
1139 {
1140 return armnn::DataLayout::NCHW;
1141 }
1142 else
1143 {
1144 return armnn::DataLayout::NHWC;
1145 }
1146}
1147
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001148template<typename HalPolicy,
1149 typename HalOperation = typename HalPolicy::Operation,
1150 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001151bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1152 uint32_t outputIndex,
1153 armnn::IConnectableLayer& layer,
1154 const HalModel& model,
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001155 ConversionData& data,
1156 const armnn::Optional<armnn::TensorInfo>& outputInfo = armnn::EmptyOptional())
Mike Kellyb5fdf382019-06-11 16:35:25 +01001157{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001158 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1159 outputIndex,
1160 layer,
1161 outputIndex,
1162 model,
1163 data,
1164 outputInfo);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001165}
1166
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001167template<typename HalPolicy,
1168 typename HalOperation = typename HalPolicy::Operation,
1169 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001170bool ConvertToActivation(const HalOperation& operation,
1171 const char* operationName,
1172 const armnn::ActivationDescriptor& activationDesc,
1173 const HalModel& model,
1174 ConversionData& data)
1175{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001176 using HalOperand = typename HalPolicy::Operand;
1177
1178 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001179 if (!input.IsValid())
1180 {
1181 return Fail("%s: Input 0 is invalid", operationName);
1182 }
1183
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001184 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001185 if (!outputOperand)
1186 {
1187 return false;
1188 }
Sadik Armagan2050c232019-07-23 16:59:58 +01001189 armnn::TensorInfo outInfo = GetTensorInfoForOperand(*outputOperand);
1190 if (IsDynamicTensor(outInfo))
1191 {
Sadik Armagan61113162019-07-25 09:09:40 +01001192 if (Is12Operand(*outputOperand))
1193 {
1194 ALOGD("Output shape not set, will infer from input");
1195 outInfo.SetShape(input.GetTensorInfo().GetShape());
1196 }
1197 else
1198 {
1199 return Fail("%s: Dynamic OutputShapes are not supported in this HAL version", __func__);
1200 }
Sadik Armagan2050c232019-07-23 16:59:58 +01001201 }
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001202
1203 bool isSupported = false;
1204 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1205 IsActivationSupported,
1206 data.m_Backends,
1207 isSupported,
1208 input.GetTensorInfo(),
1209 outInfo,
1210 activationDesc);
1211 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001212 {
1213 return false;
1214 }
1215
1216 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
1217 BOOST_ASSERT(layer != nullptr);
1218 input.Connect(layer->GetInputSlot(0));
1219
Sadik Armagan2050c232019-07-23 16:59:58 +01001220 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1221 0,
1222 *layer,
1223 model,
1224 data,armnn::Optional<armnn::TensorInfo>(outInfo));
arovir01b0717b52018-09-05 17:03:25 +01001225}
1226
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001227template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001228 typename HalOperation = typename HalPolicy::Operation,
1229 typename HalModel = typename HalPolicy::Model>
1230bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1231{
1232 armnn::ActivationDescriptor desc;
1233 desc.m_Function = armnn::ActivationFunction::ReLu;
1234
1235 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1236}
1237
1238template<typename HalPolicy,
1239 typename HalOperation = typename HalPolicy::Operation,
1240 typename HalModel = typename HalPolicy::Model>
1241bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1242{
1243 armnn::ActivationDescriptor desc;
1244 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1245 desc.m_A = 1.0f;
1246 desc.m_B = -1.0f;
1247
1248 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1249}
1250
1251template<typename HalPolicy,
1252 typename HalOperation = typename HalPolicy::Operation,
1253 typename HalModel = typename HalPolicy::Model>
1254bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1255{
1256 armnn::ActivationDescriptor desc;
1257 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1258 desc.m_A = 6.0f;
1259
1260 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1261}
1262
1263template<typename HalPolicy,
1264 typename HalOperation = typename HalPolicy::Operation,
1265 typename HalModel = typename HalPolicy::Model>
1266bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1267{
1268 armnn::ActivationDescriptor desc;
1269 desc.m_Function = armnn::ActivationFunction::TanH;
1270 desc.m_A = 1.0f; // android nn does not support tanH parameters
1271 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1272
1273 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1274}
1275
1276template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001277 typename HalOperation = typename HalPolicy::Operation,
1278 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001279bool ConvertPaddings(const HalOperation& operation,
1280 const HalModel& model,
1281 ConversionData& data,
1282 unsigned int rank,
1283 armnn::PadDescriptor& padDescriptor)
1284{
1285 using HalOperand = typename HalPolicy::Operand;
1286
1287 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1288 if (!paddingsOperand)
1289 {
1290 return Fail("%s: Could not read paddings operand", __func__);
1291 }
1292
1293 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1294 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1295 {
1296 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1297 }
1298
1299 std::vector<int32_t> paddings;
1300 GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data);
1301
1302 // add padding for each dimension of input tensor.
1303 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1304 {
1305 int paddingBeforeInput = paddings[i];
1306 int paddingAfterInput = paddings[i + 1];
1307
1308 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1309 {
1310 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1311 }
1312
1313 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1314 }
1315
1316 return true;
1317}
1318
1319template<typename HalPolicy,
1320 typename HalOperation = typename HalPolicy::Operation,
1321 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001322bool ConvertPooling2d(const HalOperation& operation,
1323 const char* operationName,
1324 armnn::PoolingAlgorithm poolType,
1325 const HalModel& model,
1326 ConversionData& data)
1327{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001328 using HalOperand = typename HalPolicy::Operand;
1329 using HalOperandType = typename HalPolicy::OperandType;
1330
1331 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001332 if (!input.IsValid())
1333 {
1334 return Fail("%s: Could not read input 0", operationName);
1335 }
1336
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001337 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001338 if (!output)
1339 {
1340 return Fail("%s: Could not read output 0", __func__);
1341 }
1342
1343 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1344 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1345
arovir01b0717b52018-09-05 17:03:25 +01001346 armnn::Pooling2dDescriptor desc;
1347 desc.m_PoolType = poolType;
1348 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001349 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001350
1351 ActivationFn activation;
1352
1353 if (operation.inputs.size() == 7)
1354 {
1355 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1356 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001357 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1358 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1359 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1360 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1361 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1362 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001363 {
1364 return Fail("%s: Operation has invalid inputs", operationName);
1365 }
1366
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001367 const unsigned int inputWidth = inputInfo.GetShape()[2];
1368 const unsigned int inputHeight = inputInfo.GetShape()[1];
arovir01b0717b52018-09-05 17:03:25 +01001369
1370 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1371 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
1372 }
1373 else
1374 {
1375 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001376 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1377 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1378 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1379 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1380 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1381 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1382 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1383 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1384 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001385 {
1386 return Fail("%s: Operation has invalid inputs", operationName);
1387 }
1388 }
1389
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001390 bool isSupported = false;
1391 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1392 IsPooling2dSupported,
1393 data.m_Backends,
1394 isSupported,
1395 inputInfo,
1396 outputInfo,
1397 desc);
1398 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001399 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001400 return false;
arovir01b0717b52018-09-05 17:03:25 +01001401 }
arovir01b0717b52018-09-05 17:03:25 +01001402
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001403 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1404 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001405 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001406 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001407 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001408
1409 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1410 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001411 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001412 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001413 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001414
1415 input.Connect(pooling2dLayer->GetInputSlot(0));
1416
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001417 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001418}
1419
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001420template<typename HalPolicy,
1421 typename HalOperation = typename HalPolicy::Operation,
1422 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001423bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1424{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001425 using HalOperand = typename HalPolicy::Operand;
1426 using HalOperandType = typename HalPolicy::OperandType;
1427
1428 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001429 if (!input.IsValid())
1430 {
1431 return Fail("%s: Operation has invalid inputs", __func__);
1432 }
1433
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001434 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001435 if (!output)
1436 {
1437 return Fail("%s: Could not read output 0", __func__);
1438 }
1439
1440 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Sadik Armagan2050c232019-07-23 16:59:58 +01001441 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001442
1443 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001444 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
1445 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001446
1447 if (!weightsPin.IsValid() || !biasPin.IsValid())
1448 {
1449 return Fail("%s: Operation has invalid inputs", __func__);
1450 }
1451
1452 armnn::ConstTensor weights = weightsPin.GetConstTensor();
1453 armnn::ConstTensor bias = biasPin.GetConstTensor();
1454 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1455
1456 armnn::Convolution2dDescriptor desc;
1457 desc.m_DataLayout = armnn::DataLayout::NHWC;
1458 ActivationFn activation;
1459
1460 if (operation.inputs.size() >= 10)
1461 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001462 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1463 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1464 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1465 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1466 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1467 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1468 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data) ||
1469 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 11, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001470 {
1471 return Fail("%s: Operation has invalid inputs", __func__);
1472 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001473 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001474 }
1475 else if (operation.inputs.size() >= 7)
1476 {
1477 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001478 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1479 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1480 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1481 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data) ||
1482 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 8, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001483 {
1484 return Fail("%s: Operation has invalid inputs", __func__);
1485 }
1486
1487 const uint32_t kernelX = weights.GetShape()[2];
1488 const uint32_t kernelY = weights.GetShape()[1];
1489 const uint32_t inputX = inputInfo.GetShape()[2];
1490 const uint32_t inputY = inputInfo.GetShape()[1];
1491
1492 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1493 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
1494
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001495 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001496 }
1497 else
1498 {
1499 return Fail("%s: Unsupported number of operation inputs", __func__);
1500 }
1501
1502 desc.m_BiasEnabled = true;
1503 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1504
Sadik Armagan2050c232019-07-23 16:59:58 +01001505 if (IsDynamicTensor(outputInfo))
1506 {
Sadik Armagan61113162019-07-25 09:09:40 +01001507 return Fail("%s: Dynamic OutputShapes are not supported", __func__);
Sadik Armagan2050c232019-07-23 16:59:58 +01001508 }
1509
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001510 bool isSupported = false;
1511 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1512 IsConvolution2dSupported,
1513 data.m_Backends,
1514 isSupported,
1515 inputInfo,
1516 outputInfo,
1517 desc,
1518 weights.GetInfo(),
1519 biases);
1520 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001521 {
1522 return false;
1523 }
1524
1525 armnn::IConnectableLayer* startLayer =
1526 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1527
1528 if (!startLayer)
1529 {
1530 return Fail("%s: AddConvolution2dLayer failed", __func__);
1531 }
1532
1533 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1534
1535 if (!endLayer)
1536 {
1537 return Fail("%s: ProcessActivation failed", __func__);
1538 }
1539
1540 input.Connect(startLayer->GetInputSlot(0));
1541
Sadik Armagan2050c232019-07-23 16:59:58 +01001542 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1543 0,
1544 *endLayer,
1545 model,
1546 data,
1547 armnn::Optional<armnn::TensorInfo>(outputInfo));
Mike Kellyb5fdf382019-06-11 16:35:25 +01001548}
1549
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001550template<typename HalPolicy,
1551 typename HalOperation = typename HalPolicy::Operation,
1552 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001553bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1554{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001555 using HalOperand = typename HalPolicy::Operand;
1556 using HalOperandType = typename HalPolicy::OperandType;
1557
1558 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001559
1560 if (!input.IsValid())
1561 {
1562 return Fail("%s: Operation has invalid inputs", __func__);
1563 }
1564
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001565 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001566
1567 if (!output)
1568 {
1569 return Fail("%s: Could not read output 0", __func__);
1570 }
1571
1572 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Sadik Armagan2050c232019-07-23 16:59:58 +01001573 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001574
1575 // ArmNN does not currently support non-fixed weights or bias
1576
1577 // 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 +01001578 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001579
1580 if (weightsOperand == nullptr)
1581 {
1582 return Fail("%s: Operand is invalid", __func__);
1583 }
1584 armnn::DepthwiseConvolution2dDescriptor desc;
1585 desc.m_DataLayout = armnn::DataLayout::NHWC;
1586
1587 // Look ahead to find the optional DataLayout, if present
1588 if (operation.inputs.size() >= 12)
1589 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001590 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 11, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001591 }
1592 else if (operation.inputs.size() >= 9)
1593 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001594 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 8, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001595 }
1596
1597 armnnUtils::DataLayoutIndexed dataLayoutIndexed(desc.m_DataLayout);
1598 unsigned int channelsIndex = dataLayoutIndexed.GetChannelsIndex();
1599 unsigned int widthIndex = dataLayoutIndexed.GetWidthIndex();
1600 unsigned int heightIndex = dataLayoutIndexed.GetHeightIndex();
1601
1602 // Reinterpret weight data as [ H, W, I, M ]
1603 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
1604 weightsOperand->dimensions[2],
1605 inputInfo.GetShape()[channelsIndex],
1606 weightsOperand->dimensions[3] / inputInfo.GetShape()[channelsIndex] });
1607
1608 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
1609 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
1610
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001611 const ConstTensorPin weightsPin =
1612 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
1613 1,
1614 model,
1615 data,
1616 HWIMToMIHW,
1617 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001618
1619 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001620 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001621
1622 if (!weightsPin.IsValid() || !biasPin.IsValid())
1623 {
1624 return Fail("%s: Operation has invalid inputs", __func__);
1625 }
1626
1627 armnn::ConstTensor weights = weightsPin.GetConstTensor();
1628 armnn::ConstTensor bias = biasPin.GetConstTensor();
1629 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1630
1631 ActivationFn activation;
1632
1633 if (operation.inputs.size() >= 11)
1634 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001635 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1636 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1637 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1638 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1639 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1640 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1641 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data) ||
1642 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 12, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001643 {
1644 return Fail("%s: Operation has invalid inputs", __func__);
1645 }
1646 }
1647 else if (operation.inputs.size() >= 8)
1648 {
1649 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001650 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1651 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1652 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1653 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data) ||
1654 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 9, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001655 {
1656 return Fail("%s: Operation has invalid inputs", __func__);
1657 }
1658
1659 const uint32_t kernelX = weights.GetShape()[3];
1660 const uint32_t kernelY = weights.GetShape()[2];
1661 const uint32_t inputX = inputInfo.GetShape()[widthIndex];
1662 const uint32_t inputY = inputInfo.GetShape()[heightIndex];
1663
1664 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1665 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
1666 }
1667 else
1668 {
1669 return Fail("%s: Unsupported number of operation inputs", __func__);
1670 }
1671
1672 desc.m_BiasEnabled = true;
1673 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1674
Sadik Armagan2050c232019-07-23 16:59:58 +01001675 if (IsDynamicTensor(outputInfo))
1676 {
Sadik Armagan61113162019-07-25 09:09:40 +01001677 return Fail("%s: Dynamic OutputShapes are not supported", __func__);
Sadik Armagan2050c232019-07-23 16:59:58 +01001678 }
1679
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001680 bool isSupported = false;
1681 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1682 IsDepthwiseConvolutionSupported,
1683 data.m_Backends,
1684 isSupported,
1685 inputInfo,
1686 outputInfo,
1687 desc,
1688 weights.GetInfo(),
1689 biases);
1690 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001691 {
1692 return false;
1693 }
1694
1695 armnn::IConnectableLayer* startLayer =
1696 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1697 if (!startLayer)
1698 {
1699 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
1700 }
1701
1702 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1703 if (!endLayer)
1704 {
1705 return Fail("%s: ProcessActivation failed", __func__);
1706 }
1707
1708 input.Connect(startLayer->GetInputSlot(0));
1709
Sadik Armagan2050c232019-07-23 16:59:58 +01001710 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1711 0,
1712 *endLayer,
1713 model,
1714 data,
1715 armnn::Optional<armnn::TensorInfo>(outputInfo));
arovir01b0717b52018-09-05 17:03:25 +01001716}
1717
Mike Kelly3c673942019-07-25 09:26:06 +01001718template<typename HalPolicy,
1719 typename HalOperation = typename HalPolicy::Operation,
1720 typename HalOperand = typename HalPolicy::Operand,
1721 typename HalModel = typename HalPolicy::Model>
1722bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
1723{
Mike Kelly3c673942019-07-25 09:26:06 +01001724 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1725 if (!input.IsValid())
1726 {
1727 return Fail("%s: Operation has invalid inputs", __func__);
1728 }
1729
1730 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1731 unsigned int rank = inputInfo.GetNumDimensions();
1732
1733 armnn::PadDescriptor descriptor;
1734 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
1735 {
1736 return Fail("%s: Could not convert paddings", __func__);
1737 }
1738
1739 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
1740 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
1741 // (QuantizationOffset - QuantizationOffset) * scale = 0.
1742 if (inputInfo.GetDataType() == armnn::DataType::QuantisedAsymm8)
1743 {
1744 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
1745 }
1746
1747 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1748 if (!output)
1749 {
1750 return Fail("%s: Could not read output", __func__);
1751 }
1752
1753 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
1754 if (IsDynamicTensor(outputInfo))
1755 {
1756 ALOGD("Output shape not set, will infer from inputs");
1757 outputInfo.SetShape(InferPadOutputShape(inputInfo.GetShape(), descriptor.m_PadList));
1758 }
1759
1760 bool isSupported = false;
1761 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1762 IsPadSupported,
1763 data.m_Backends,
1764 isSupported,
1765 inputInfo,
1766 outputInfo,
1767 descriptor);
1768 if (!isSupported)
1769 {
1770 return false;
1771 }
1772
1773 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
1774 assert(layer != nullptr);
1775 input.Connect(layer->GetInputSlot(0));
1776 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1777
1778 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1779 0,
1780 *layer,
1781 model,
1782 data,
1783 armnn::Optional<armnn::TensorInfo>(outputInfo));
1784}
1785
saoste01b8471482018-10-10 09:44:51 +01001786} // namespace armnn_driver