blob: 790382d6e1b6c621a68c74a4eb8e5fa34b17ff3e [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::TEMPORARY_VARIABLE: // intentional fallthrough
998 case HalOperandLifeTime::MODEL_INPUT:
999 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001000 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001001 // The tensor is either an operand internal to the model, or a model input.
1002 // It can be associated with an ArmNN output slot for an existing layer.
1003
1004 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1005 const uint32_t operandIndex = operation.inputs[inputIndex];
1006 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1007 break;
1008 }
1009 case HalOperandLifeTime::CONSTANT_COPY:
1010 case HalOperandLifeTime::CONSTANT_REFERENCE:
1011 {
1012 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1013 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1014 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001015 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001016 bool isSupported = false;
1017 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1018 IsConstantSupported,
1019 data.m_Backends,
1020 isSupported,
1021 tensorPin.GetConstTensor().GetInfo());
1022 if (isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001023 {
1024 return LayerInputHandle();
1025 }
1026
1027 armnn::IConnectableLayer* constantLayer =
1028 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1029 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1030 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1031
1032 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1033 }
1034 else
1035 {
1036 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001037 return LayerInputHandle();
1038 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001039 break;
arovir01b0717b52018-09-05 17:03:25 +01001040 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001041 default:
arovir01b0717b52018-09-05 17:03:25 +01001042 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001043 // Unsupported lifetime for an input tensor
1044 Fail("%s: unsupported lifetime for input tensor: %s",
1045 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001046 return LayerInputHandle();
1047 }
arovir01b0717b52018-09-05 17:03:25 +01001048 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001049 }
1050 catch (UnsupportedOperand<HalOperandType>& e)
1051 {
1052 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1053 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001054 }
1055}
1056
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001057template<typename HalPolicy,
1058 typename HalOperation = typename HalPolicy::Operation,
1059 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001060bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1061 uint32_t operationOutputIndex,
1062 armnn::IConnectableLayer& layer,
1063 uint32_t layerOutputIndex,
1064 const HalModel& model,
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001065 ConversionData& data,
1066 const armnn::Optional<armnn::TensorInfo>& outputInfo = armnn::EmptyOptional())
Mike Kellyb5fdf382019-06-11 16:35:25 +01001067{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001068 using HalOperand = typename HalPolicy::Operand;
1069
1070 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001071 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1072 {
1073 return false;
1074 }
1075
1076 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
1077
1078 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1079 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1080
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001081 if (outputInfo.has_value())
1082 {
1083 outputSlot.SetTensorInfo(outputInfo.value());
1084 ALOGD("Output info overwritten");
1085 }
1086 else
1087 {
1088 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1089 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001090
1091 return true;
1092}
1093
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001094template<typename HalPolicy,
1095 typename HalOperation = typename HalPolicy::Operation,
1096 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001097armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1098 uint32_t inputIndex,
1099 const HalModel& model,
1100 ConversionData& data)
1101{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001102 using HalOperand = typename HalPolicy::Operand;
1103
1104 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001105 if (!operand)
1106 {
1107 return armnn::DataLayout::NHWC;
1108 }
1109
1110 if (!IsBool(*operand))
1111 {
1112 return armnn::DataLayout::NHWC;
1113 }
1114
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001115 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001116 if (!valueAddress)
1117 {
1118 return armnn::DataLayout::NHWC;
1119 }
1120
1121 if (*(static_cast<const bool*>(valueAddress)))
1122 {
1123 return armnn::DataLayout::NCHW;
1124 }
1125 else
1126 {
1127 return armnn::DataLayout::NHWC;
1128 }
1129}
1130
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001131template<typename HalPolicy,
1132 typename HalOperation = typename HalPolicy::Operation,
1133 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001134bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1135 uint32_t outputIndex,
1136 armnn::IConnectableLayer& layer,
1137 const HalModel& model,
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001138 ConversionData& data,
1139 const armnn::Optional<armnn::TensorInfo>& outputInfo = armnn::EmptyOptional())
Mike Kellyb5fdf382019-06-11 16:35:25 +01001140{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001141 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1142 outputIndex,
1143 layer,
1144 outputIndex,
1145 model,
1146 data,
1147 outputInfo);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001148}
1149
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001150template<typename HalPolicy,
1151 typename HalOperation = typename HalPolicy::Operation,
1152 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001153bool ConvertToActivation(const HalOperation& operation,
1154 const char* operationName,
1155 const armnn::ActivationDescriptor& activationDesc,
1156 const HalModel& model,
1157 ConversionData& data)
1158{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001159 using HalOperand = typename HalPolicy::Operand;
1160
1161 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001162 if (!input.IsValid())
1163 {
1164 return Fail("%s: Input 0 is invalid", operationName);
1165 }
1166
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001167 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001168 if (!outputOperand)
1169 {
1170 return false;
1171 }
Sadik Armagan2050c232019-07-23 16:59:58 +01001172 armnn::TensorInfo outInfo = GetTensorInfoForOperand(*outputOperand);
1173 if (IsDynamicTensor(outInfo))
1174 {
Sadik Armagan61113162019-07-25 09:09:40 +01001175 if (Is12Operand(*outputOperand))
1176 {
1177 ALOGD("Output shape not set, will infer from input");
1178 outInfo.SetShape(input.GetTensorInfo().GetShape());
1179 }
1180 else
1181 {
1182 return Fail("%s: Dynamic OutputShapes are not supported in this HAL version", __func__);
1183 }
Sadik Armagan2050c232019-07-23 16:59:58 +01001184 }
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001185
1186 bool isSupported = false;
1187 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1188 IsActivationSupported,
1189 data.m_Backends,
1190 isSupported,
1191 input.GetTensorInfo(),
1192 outInfo,
1193 activationDesc);
1194 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001195 {
1196 return false;
1197 }
1198
1199 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
1200 BOOST_ASSERT(layer != nullptr);
1201 input.Connect(layer->GetInputSlot(0));
1202
Sadik Armagan2050c232019-07-23 16:59:58 +01001203 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1204 0,
1205 *layer,
1206 model,
1207 data,armnn::Optional<armnn::TensorInfo>(outInfo));
arovir01b0717b52018-09-05 17:03:25 +01001208}
1209
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001210template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001211 typename HalOperation = typename HalPolicy::Operation,
1212 typename HalModel = typename HalPolicy::Model>
1213bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1214{
1215 armnn::ActivationDescriptor desc;
1216 desc.m_Function = armnn::ActivationFunction::ReLu;
1217
1218 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1219}
1220
1221template<typename HalPolicy,
1222 typename HalOperation = typename HalPolicy::Operation,
1223 typename HalModel = typename HalPolicy::Model>
1224bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1225{
1226 armnn::ActivationDescriptor desc;
1227 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1228 desc.m_A = 1.0f;
1229 desc.m_B = -1.0f;
1230
1231 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1232}
1233
1234template<typename HalPolicy,
1235 typename HalOperation = typename HalPolicy::Operation,
1236 typename HalModel = typename HalPolicy::Model>
1237bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1238{
1239 armnn::ActivationDescriptor desc;
1240 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1241 desc.m_A = 6.0f;
1242
1243 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1244}
1245
1246template<typename HalPolicy,
1247 typename HalOperation = typename HalPolicy::Operation,
1248 typename HalModel = typename HalPolicy::Model>
1249bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1250{
1251 armnn::ActivationDescriptor desc;
1252 desc.m_Function = armnn::ActivationFunction::TanH;
1253 desc.m_A = 1.0f; // android nn does not support tanH parameters
1254 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1255
1256 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1257}
1258
1259template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001260 typename HalOperation = typename HalPolicy::Operation,
1261 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001262bool ConvertPaddings(const HalOperation& operation,
1263 const HalModel& model,
1264 ConversionData& data,
1265 unsigned int rank,
1266 armnn::PadDescriptor& padDescriptor)
1267{
1268 using HalOperand = typename HalPolicy::Operand;
1269
1270 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1271 if (!paddingsOperand)
1272 {
1273 return Fail("%s: Could not read paddings operand", __func__);
1274 }
1275
1276 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1277 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1278 {
1279 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1280 }
1281
1282 std::vector<int32_t> paddings;
1283 GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data);
1284
1285 // add padding for each dimension of input tensor.
1286 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1287 {
1288 int paddingBeforeInput = paddings[i];
1289 int paddingAfterInput = paddings[i + 1];
1290
1291 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1292 {
1293 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1294 }
1295
1296 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1297 }
1298
1299 return true;
1300}
1301
1302template<typename HalPolicy,
1303 typename HalOperation = typename HalPolicy::Operation,
1304 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001305bool ConvertPooling2d(const HalOperation& operation,
1306 const char* operationName,
1307 armnn::PoolingAlgorithm poolType,
1308 const HalModel& model,
1309 ConversionData& data)
1310{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001311 using HalOperand = typename HalPolicy::Operand;
1312 using HalOperandType = typename HalPolicy::OperandType;
1313
1314 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001315 if (!input.IsValid())
1316 {
1317 return Fail("%s: Could not read input 0", operationName);
1318 }
1319
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001320 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001321 if (!output)
1322 {
1323 return Fail("%s: Could not read output 0", __func__);
1324 }
1325
1326 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1327 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1328
arovir01b0717b52018-09-05 17:03:25 +01001329 armnn::Pooling2dDescriptor desc;
1330 desc.m_PoolType = poolType;
1331 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001332 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001333
1334 ActivationFn activation;
1335
1336 if (operation.inputs.size() == 7)
1337 {
1338 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1339 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001340 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1341 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1342 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1343 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1344 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1345 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001346 {
1347 return Fail("%s: Operation has invalid inputs", operationName);
1348 }
1349
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001350 const unsigned int inputWidth = inputInfo.GetShape()[2];
1351 const unsigned int inputHeight = inputInfo.GetShape()[1];
arovir01b0717b52018-09-05 17:03:25 +01001352
1353 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1354 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
1355 }
1356 else
1357 {
1358 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001359 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1360 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1361 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1362 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1363 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1364 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1365 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1366 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1367 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001368 {
1369 return Fail("%s: Operation has invalid inputs", operationName);
1370 }
1371 }
1372
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001373 bool isSupported = false;
1374 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1375 IsPooling2dSupported,
1376 data.m_Backends,
1377 isSupported,
1378 inputInfo,
1379 outputInfo,
1380 desc);
1381 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001382 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001383 return false;
arovir01b0717b52018-09-05 17:03:25 +01001384 }
arovir01b0717b52018-09-05 17:03:25 +01001385
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001386 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1387 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001388 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001389 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001390 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001391
1392 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1393 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001394 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001395 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001396 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001397
1398 input.Connect(pooling2dLayer->GetInputSlot(0));
1399
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001400 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001401}
1402
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001403template<typename HalPolicy,
1404 typename HalOperation = typename HalPolicy::Operation,
1405 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001406bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1407{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001408 using HalOperand = typename HalPolicy::Operand;
1409 using HalOperandType = typename HalPolicy::OperandType;
1410
1411 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001412 if (!input.IsValid())
1413 {
1414 return Fail("%s: Operation has invalid inputs", __func__);
1415 }
1416
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001417 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001418 if (!output)
1419 {
1420 return Fail("%s: Could not read output 0", __func__);
1421 }
1422
1423 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Sadik Armagan2050c232019-07-23 16:59:58 +01001424 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001425
1426 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001427 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
1428 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001429
1430 if (!weightsPin.IsValid() || !biasPin.IsValid())
1431 {
1432 return Fail("%s: Operation has invalid inputs", __func__);
1433 }
1434
1435 armnn::ConstTensor weights = weightsPin.GetConstTensor();
1436 armnn::ConstTensor bias = biasPin.GetConstTensor();
1437 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1438
1439 armnn::Convolution2dDescriptor desc;
1440 desc.m_DataLayout = armnn::DataLayout::NHWC;
1441 ActivationFn activation;
1442
1443 if (operation.inputs.size() >= 10)
1444 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001445 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1446 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1447 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1448 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1449 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1450 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1451 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data) ||
1452 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 11, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001453 {
1454 return Fail("%s: Operation has invalid inputs", __func__);
1455 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001456 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001457 }
1458 else if (operation.inputs.size() >= 7)
1459 {
1460 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001461 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1462 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1463 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1464 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data) ||
1465 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 8, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001466 {
1467 return Fail("%s: Operation has invalid inputs", __func__);
1468 }
1469
1470 const uint32_t kernelX = weights.GetShape()[2];
1471 const uint32_t kernelY = weights.GetShape()[1];
1472 const uint32_t inputX = inputInfo.GetShape()[2];
1473 const uint32_t inputY = inputInfo.GetShape()[1];
1474
1475 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1476 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
1477
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001478 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001479 }
1480 else
1481 {
1482 return Fail("%s: Unsupported number of operation inputs", __func__);
1483 }
1484
1485 desc.m_BiasEnabled = true;
1486 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1487
Sadik Armagan2050c232019-07-23 16:59:58 +01001488 if (IsDynamicTensor(outputInfo))
1489 {
Sadik Armagan61113162019-07-25 09:09:40 +01001490 return Fail("%s: Dynamic OutputShapes are not supported", __func__);
Sadik Armagan2050c232019-07-23 16:59:58 +01001491 }
1492
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001493 bool isSupported = false;
1494 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1495 IsConvolution2dSupported,
1496 data.m_Backends,
1497 isSupported,
1498 inputInfo,
1499 outputInfo,
1500 desc,
1501 weights.GetInfo(),
1502 biases);
1503 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001504 {
1505 return false;
1506 }
1507
1508 armnn::IConnectableLayer* startLayer =
1509 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1510
1511 if (!startLayer)
1512 {
1513 return Fail("%s: AddConvolution2dLayer failed", __func__);
1514 }
1515
1516 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1517
1518 if (!endLayer)
1519 {
1520 return Fail("%s: ProcessActivation failed", __func__);
1521 }
1522
1523 input.Connect(startLayer->GetInputSlot(0));
1524
Sadik Armagan2050c232019-07-23 16:59:58 +01001525 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1526 0,
1527 *endLayer,
1528 model,
1529 data,
1530 armnn::Optional<armnn::TensorInfo>(outputInfo));
Mike Kellyb5fdf382019-06-11 16:35:25 +01001531}
1532
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001533template<typename HalPolicy,
1534 typename HalOperation = typename HalPolicy::Operation,
1535 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001536bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
1537{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001538 using HalOperand = typename HalPolicy::Operand;
1539 using HalOperandType = typename HalPolicy::OperandType;
1540
1541 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001542
1543 if (!input.IsValid())
1544 {
1545 return Fail("%s: Operation has invalid inputs", __func__);
1546 }
1547
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001548 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001549
1550 if (!output)
1551 {
1552 return Fail("%s: Could not read output 0", __func__);
1553 }
1554
1555 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Sadik Armagan2050c232019-07-23 16:59:58 +01001556 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001557
1558 // ArmNN does not currently support non-fixed weights or bias
1559
1560 // 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 +01001561 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001562
1563 if (weightsOperand == nullptr)
1564 {
1565 return Fail("%s: Operand is invalid", __func__);
1566 }
1567 armnn::DepthwiseConvolution2dDescriptor desc;
1568 desc.m_DataLayout = armnn::DataLayout::NHWC;
1569
1570 // Look ahead to find the optional DataLayout, if present
1571 if (operation.inputs.size() >= 12)
1572 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001573 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 11, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001574 }
1575 else if (operation.inputs.size() >= 9)
1576 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001577 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 8, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001578 }
1579
1580 armnnUtils::DataLayoutIndexed dataLayoutIndexed(desc.m_DataLayout);
1581 unsigned int channelsIndex = dataLayoutIndexed.GetChannelsIndex();
1582 unsigned int widthIndex = dataLayoutIndexed.GetWidthIndex();
1583 unsigned int heightIndex = dataLayoutIndexed.GetHeightIndex();
1584
1585 // Reinterpret weight data as [ H, W, I, M ]
1586 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
1587 weightsOperand->dimensions[2],
1588 inputInfo.GetShape()[channelsIndex],
1589 weightsOperand->dimensions[3] / inputInfo.GetShape()[channelsIndex] });
1590
1591 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
1592 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
1593
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001594 const ConstTensorPin weightsPin =
1595 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
1596 1,
1597 model,
1598 data,
1599 HWIMToMIHW,
1600 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001601
1602 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001603 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001604
1605 if (!weightsPin.IsValid() || !biasPin.IsValid())
1606 {
1607 return Fail("%s: Operation has invalid inputs", __func__);
1608 }
1609
1610 armnn::ConstTensor weights = weightsPin.GetConstTensor();
1611 armnn::ConstTensor bias = biasPin.GetConstTensor();
1612 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
1613
1614 ActivationFn activation;
1615
1616 if (operation.inputs.size() >= 11)
1617 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001618 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1619 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1620 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1621 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1622 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1623 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1624 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data) ||
1625 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 12, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001626 {
1627 return Fail("%s: Operation has invalid inputs", __func__);
1628 }
1629 }
1630 else if (operation.inputs.size() >= 8)
1631 {
1632 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001633 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
1634 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1635 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1636 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data) ||
1637 !GetOptionalConvolutionDilationParams<HalPolicy>(operation, 9, desc, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01001638 {
1639 return Fail("%s: Operation has invalid inputs", __func__);
1640 }
1641
1642 const uint32_t kernelX = weights.GetShape()[3];
1643 const uint32_t kernelY = weights.GetShape()[2];
1644 const uint32_t inputX = inputInfo.GetShape()[widthIndex];
1645 const uint32_t inputY = inputInfo.GetShape()[heightIndex];
1646
1647 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
1648 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
1649 }
1650 else
1651 {
1652 return Fail("%s: Unsupported number of operation inputs", __func__);
1653 }
1654
1655 desc.m_BiasEnabled = true;
1656 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
1657
Sadik Armagan2050c232019-07-23 16:59:58 +01001658 if (IsDynamicTensor(outputInfo))
1659 {
Sadik Armagan61113162019-07-25 09:09:40 +01001660 return Fail("%s: Dynamic OutputShapes are not supported", __func__);
Sadik Armagan2050c232019-07-23 16:59:58 +01001661 }
1662
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001663 bool isSupported = false;
1664 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1665 IsDepthwiseConvolutionSupported,
1666 data.m_Backends,
1667 isSupported,
1668 inputInfo,
1669 outputInfo,
1670 desc,
1671 weights.GetInfo(),
1672 biases);
1673 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001674 {
1675 return false;
1676 }
1677
1678 armnn::IConnectableLayer* startLayer =
1679 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
1680 if (!startLayer)
1681 {
1682 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
1683 }
1684
1685 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
1686 if (!endLayer)
1687 {
1688 return Fail("%s: ProcessActivation failed", __func__);
1689 }
1690
1691 input.Connect(startLayer->GetInputSlot(0));
1692
Sadik Armagan2050c232019-07-23 16:59:58 +01001693 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1694 0,
1695 *endLayer,
1696 model,
1697 data,
1698 armnn::Optional<armnn::TensorInfo>(outputInfo));
arovir01b0717b52018-09-05 17:03:25 +01001699}
1700
Mike Kelly3c673942019-07-25 09:26:06 +01001701template<typename HalPolicy,
1702 typename HalOperation = typename HalPolicy::Operation,
1703 typename HalOperand = typename HalPolicy::Operand,
1704 typename HalModel = typename HalPolicy::Model>
1705bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
1706{
Mike Kelly3c673942019-07-25 09:26:06 +01001707 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1708 if (!input.IsValid())
1709 {
1710 return Fail("%s: Operation has invalid inputs", __func__);
1711 }
1712
1713 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1714 unsigned int rank = inputInfo.GetNumDimensions();
1715
1716 armnn::PadDescriptor descriptor;
1717 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
1718 {
1719 return Fail("%s: Could not convert paddings", __func__);
1720 }
1721
1722 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
1723 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
1724 // (QuantizationOffset - QuantizationOffset) * scale = 0.
1725 if (inputInfo.GetDataType() == armnn::DataType::QuantisedAsymm8)
1726 {
1727 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
1728 }
1729
1730 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1731 if (!output)
1732 {
1733 return Fail("%s: Could not read output", __func__);
1734 }
1735
1736 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*output);
1737 if (IsDynamicTensor(outputInfo))
1738 {
1739 ALOGD("Output shape not set, will infer from inputs");
1740 outputInfo.SetShape(InferPadOutputShape(inputInfo.GetShape(), descriptor.m_PadList));
1741 }
1742
1743 bool isSupported = false;
1744 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1745 IsPadSupported,
1746 data.m_Backends,
1747 isSupported,
1748 inputInfo,
1749 outputInfo,
1750 descriptor);
1751 if (!isSupported)
1752 {
1753 return false;
1754 }
1755
1756 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
1757 assert(layer != nullptr);
1758 input.Connect(layer->GetInputSlot(0));
1759 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
1760
1761 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1762 0,
1763 *layer,
1764 model,
1765 data,
1766 armnn::Optional<armnn::TensorInfo>(outputInfo));
1767}
1768
saoste01b8471482018-10-10 09:44:51 +01001769} // namespace armnn_driver