blob: 74e26f2a2575cee29a7749b4bc84cbf2bbecb28c [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
8#include <armnn/ArmNN.hpp>
9
10#include "armnn/src/armnnUtils/Permute.hpp"
11#include "Utils.hpp"
12
13#include <ActivationFunctor.h>
14#include <CpuExecutor.h>
15#include <OperationsUtils.h>
16
17#include <boost/assert.hpp>
18#include <boost/core/ignore_unused.hpp>
Aron Virginas-Tar0e7ab542019-04-10 15:02:31 +010019#include <boost/numeric/conversion/cast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010020#include <boost/test/tools/floating_point_comparison.hpp>
21
22#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010023#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010024
25namespace armnn_driver
26{
27
28///
29/// Helper classes
30///
31
32struct ConversionData
33{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010034 ConversionData(const std::vector<armnn::BackendId>& backends)
35 : m_Backends(backends)
36 , m_Network(nullptr, nullptr)
arovir01b0717b52018-09-05 17:03:25 +010037 {}
38
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010039 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010040 armnn::INetworkPtr m_Network;
41 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
42 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
43};
44
45class LayerInputHandle
46{
47public:
48 LayerInputHandle();
49 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
50
51 bool IsValid() const;
52
53 void Connect(armnn::IInputSlot& inputSlot);
54
55 const armnn::TensorInfo& GetTensorInfo() const;
56
57private:
58 armnn::IOutputSlot* m_OutputSlot;
59 bool m_Valid;
60 armnn::TensorInfo m_TensorInfo;
61};
62
63class ConstTensorPin
64{
65public:
66 // Creates an invalid tensor pin (can be used to signal errors)
67 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
68 ConstTensorPin(bool optional = false);
69
70 // @param tensorInfo TensorInfo associated with the tensor.
71 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
72 // the model being converted.
73 // @param numBytes Number of bytes for the tensor data.
74 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
75 const armnn::PermutationVector& mappings);
76
77 ConstTensorPin(const ConstTensorPin& other) = delete;
78 ConstTensorPin(ConstTensorPin&& other) = default;
79
80 bool IsValid() const;
81 bool IsOptional() const;
82
83 const armnn::ConstTensor& GetConstTensor() const;
84 const armnn::ConstTensor* GetConstTensorPtr() const;
85
86private:
87 armnn::ConstTensor m_ConstTensor;
88
89 // Owned memory for swizzled tensor data, only required if the tensor needed
90 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
91 // the pools associated with the model being converted.
92 std::vector<uint8_t> m_SwizzledTensorData;
93
94 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
95 bool m_Optional;
96};
97
98} // namespace armnn_driver
99
100///
101/// Utility functions
102///
103
104namespace
105{
106
107using namespace armnn_driver;
108using namespace android::nn;
109
110// Convenience function to log the reason for failing to convert a model.
111// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
112template<class... Args>
113static bool Fail(const char* formatStr, Args&&... args)
114{
115 ALOGD(formatStr, std::forward<Args>(args)...);
116 return false;
117}
118
119// Convenience function to call an Is*Supported function and log caller name together with reason for lack of support.
120// Called as: IsLayerSupported(__func__, Is*Supported, a, b, c, d, e)
121template<typename IsLayerSupportedFunc, typename ... Args>
122bool IsLayerSupported(const char* funcName, IsLayerSupportedFunc f, Args&&... args)
123{
124 std::vector<char> unsupportedReason(1024+1);
125 bool isSupported = f(std::forward<Args>(args)..., unsupportedReason.data(), unsupportedReason.size()-1);
126 if(isSupported)
127 {
128 return true;
129 }
130 else
131 {
132 std::string sUnsupportedReason(unsupportedReason.data());
133 if (sUnsupportedReason.size() > 0)
134 {
135 ALOGD("%s: not supported by armnn: %s", funcName, sUnsupportedReason.c_str());
136 } else
137 {
138 ALOGD("%s: not supported by armnn", funcName);
139 }
140 return false;
141 }
142}
143
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100144template<typename IsLayerSupportedFunc, typename ... Args>
145bool IsLayerSupportedForAnyBackend(const char* funcName,
146 IsLayerSupportedFunc f,
147 const std::vector<armnn::BackendId>& backends,
148 Args&&... args)
149{
150 for (auto&& backend : backends)
151 {
152 if (IsLayerSupported(funcName, f, backend, std::forward<Args>(args)...))
153 {
154 return true;
155 }
156 }
157
158 ALOGD("%s: not supported by any specified backend", funcName);
159 return false;
160}
161
arovir01b0717b52018-09-05 17:03:25 +0100162armnn::TensorShape GetTensorShapeForOperand(const Operand& operand)
163{
164 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
165}
166
167inline bool IsOperandTypeSupportedForTensors(OperandType type)
168{
169 return type == OperandType::TENSOR_FLOAT32 ||
170 type == OperandType::TENSOR_QUANT8_ASYMM ||
171 type == OperandType::TENSOR_INT32;
172}
173
174void BroadcastTensor(LayerInputHandle& input0, LayerInputHandle& input1, armnn::IConnectableLayer* startLayer,
175 armnn::INetwork& network)
176{
177 BOOST_ASSERT(startLayer != nullptr);
178 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
179 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
180
181 if (inputTensorInfo0.GetNumDimensions() != inputTensorInfo1.GetNumDimensions())
182 {
183 // If the number of dimensions do not match then we need to add degenerate dimensions
184 // to the "smaller" tensor using a reshape:
185 // Small Big
186 // | |
187 // Reshape |
188 // \ /
189 // Add
190 bool input0IsBigger = inputTensorInfo0.GetNumDimensions() > inputTensorInfo1.GetNumDimensions();
191
192 LayerInputHandle& smallTensorHandle = input0IsBigger ? input1 : input0;
193 const armnn::TensorInfo& smallTensorDims = smallTensorHandle.GetTensorInfo();
194
195 LayerInputHandle& bigTensorHandle = input0IsBigger ? input0 : input1;
196 const armnn::TensorInfo& bigTensorDims = bigTensorHandle.GetTensorInfo();
197
198 const unsigned int bigTensorDimsNumber = bigTensorDims.GetNumDimensions();
199 std::vector<unsigned int> reshapedDims(bigTensorDimsNumber, 1);
200 unsigned int sizeDifference = bigTensorDimsNumber - smallTensorDims.GetNumDimensions();
201 for (unsigned i = sizeDifference; i < bigTensorDimsNumber; ++i)
202 {
203 reshapedDims[i] = smallTensorDims.GetShape()[i-sizeDifference];
204 }
205 armnn::TensorInfo reshapedInfo = smallTensorDims;
206 reshapedInfo.SetShape(armnn::TensorShape{ static_cast<unsigned int>(reshapedDims.size()),
207 reshapedDims.data() });
208
209 armnn::ReshapeDescriptor reshapeDesc;
210 reshapeDesc.m_TargetShape = reshapedInfo.GetShape();
211 armnn::IConnectableLayer* const reshapeLayer = network.AddReshapeLayer(reshapeDesc);
212 smallTensorHandle.Connect(reshapeLayer->GetInputSlot(0));
213 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
214
215 // Connect the outputs from new reshape and original input layer
216 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
217 bigTensorHandle.Connect(startLayer->GetInputSlot(1));
218 }
219 else
220 {
221 input0.Connect(startLayer->GetInputSlot(0));
222 input1.Connect(startLayer->GetInputSlot(1));
223 }
224}
225
226void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
227 android::nn::PaddingScheme scheme)
228{
229 int32_t padHead;
230 int32_t padTail;
231 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
232 outPadHead = boost::numeric_cast<uint32_t>(padHead);
233 outPadTail = boost::numeric_cast<uint32_t>(padTail);
234}
235
236Shape GetOperandShape(const Operand& operand)
237{
238 Shape shape;
239 shape.type = operand.type;
240 shape.dimensions = operand.dimensions;
241 shape.scale = operand.scale;
242 shape.offset = operand.zeroPoint;
243 return shape;
244}
245
246// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
247// what AndroidNN requires. However for some of the AndroidNN tests the values don't exactly match so
248// we accept some tolerance. We don't want to ArmNN itself to accept these inconsistencies as it is up to the user
249// (us, in this case) to ensure they match.
250void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
251 const armnn::TensorInfo& weightInfo, const armnn::TensorInfo& inputInfo)
252{
253 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
254 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
255 {
256 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
257 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
258 {
259 ALOGW("Bias quantization scale has been modified to match input*weights");
260 biasInfo.SetQuantizationScale(expectedBiasScale);
261 }
262 }
263}
264
265// 4D Tensor Permutations
266const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
267const armnn::PermutationVector NHWCToArmNN({ 0U, 2U, 3U, 1U });
268const armnn::PermutationVector ArmNNToNHWC({ 0U, 3U, 1U, 2U });
269const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
270
271// 3D Permutation Vectors
272const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
273const armnn::PermutationVector RotateTensorLeft({ 2U, 0U, 1U });
274const armnn::PermutationVector RotateTensorRight({ 1U, 2U, 0U });
275
276template<typename OSlot>
277armnn::IConnectableLayer& AddPermuteLayer(armnn::INetwork& network, OSlot& input,
278 const armnn::PermutationVector& mappings)
279{
280 // Add swizzle layer
281 armnn::IConnectableLayer* const layer = network.AddPermuteLayer(mappings);
282
283 BOOST_ASSERT(layer != nullptr);
284
285 // Connect input to swizzle layer
286 input.Connect(layer->GetInputSlot(0));
287
288 // Setup swizzled output
289 const armnn::TensorInfo outInfo = armnnUtils::Permuted(input.GetTensorInfo(), mappings);
290 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
291
292 return *layer;
293}
294
295void SwizzleIn(armnn::INetwork& network, LayerInputHandle& input, armnn::IConnectableLayer& layer, unsigned int index)
296{
297 // Add swizzle layer
298 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, input, NHWCToArmNN);
299 // Connect swizzled input to layer
300 swizzleLayer.GetOutputSlot(0).Connect(layer.GetInputSlot(index));
301}
302
303armnn::IConnectableLayer& DeswizzleOut(armnn::INetwork& network, armnn::IConnectableLayer& layer, unsigned int index)
304{
305 // Add deswizzle layer
306 armnn::IConnectableLayer& deswizzleLayer = AddPermuteLayer(network, layer.GetOutputSlot(index), ArmNNToNHWC);
307 return deswizzleLayer;
308}
309
310// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
311armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network,
312 LayerInputHandle& input,
313 armnn::IConnectableLayer& firstLayer,
314 armnn::IConnectableLayer& lastLayer)
315{
316 SwizzleIn(network, input, firstLayer, 0);
317 return DeswizzleOut(network, lastLayer, 0);
318}
319
320// only suitable for input/output slot index 0, for other slots, use SwizzleIn and DeswizzleOut directly
321armnn::IConnectableLayer& SwizzleInDeswizzleOut(armnn::INetwork& network, LayerInputHandle& input,
322 armnn::IConnectableLayer& layer)
323{
324 return SwizzleInDeswizzleOut(network, input, layer, layer);
325}
326
327bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
328 const armnn::TensorShape & outputShape,
329 uint32_t concatDim)
330{
331 // Validate the output shape is correct given the input shapes (which have just been validated)
332 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
333 if (outputShape.GetNumDimensions() != numDimensions)
334 {
335 return Fail("%s: Output shape has wrong number of dimensions", __func__);
336 }
337
338 unsigned int outputSizeAlongConcatenatedDimension = 0;
339 for (unsigned int i = 0; i < inputShapes.size(); i++)
340 {
341 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
342 }
343
344 for (unsigned int i = 0; i < numDimensions; ++i)
345 {
346 if (i == concatDim)
347 {
348 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
349 {
350 return Fail(
351 "%s: Invalid output shape for dimension %d (%d != %d)",
352 __func__,
353 i,
354 outputShape[i],
355 outputSizeAlongConcatenatedDimension);
356 }
357 }
358 else
359 {
360 if (outputShape[i] != inputShapes[0][i])
361 {
362 return Fail("%s: Invalid output shape", __func__);
363 }
364 }
365 }
366
367 return true;
368}
369
370bool RequiresReshape(armnn::TensorShape & inputShape)
371{
372 return inputShape.GetNumDimensions() < 3;
373}
374
375template<typename OSlot>
376armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network, OSlot& inputLayer,
377 armnn::TensorInfo reshapeInfo)
378{
379 armnn::ReshapeDescriptor reshapeDescriptor;
380 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
381
382 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
383 BOOST_ASSERT(reshapeLayer != nullptr);
384
385 // Attach the input layer to the reshape layer
386 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
387 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
388
389 return *reshapeLayer;
390}
391
392void SwizzleInputs(armnn::INetwork& network,
393 std::vector<LayerInputHandle>& inputs,
394 std::vector<armnn::TensorShape>& inputShapes,
395 const armnn::PermutationVector& mapping)
396{
397 if (!mapping.IsEqual(IdentityPermutation4D))
398 {
399 size_t nInputs = inputs.size();
400 for (size_t i=0; i<nInputs; ++i)
401 {
402 // add swizzle layer
403 armnn::IConnectableLayer& swizzleLayer = AddPermuteLayer(network, inputs[i], mapping);
404 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
405 auto& outputInfo = outputSlot.GetTensorInfo();
406 // replace inputs with the swizzled ones
407 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
408 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
409 }
410 }
411}
412
narpra01f176d5a2018-11-18 20:17:48 +0000413bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
414 int32_t & concatDimension,
415 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100416{
narpra01f176d5a2018-11-18 20:17:48 +0000417 bool needPermute = false;
arovir01b0717b52018-09-05 17:03:25 +0100418 BOOST_ASSERT(numberOfDimensions >= 3);
419
420 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000421 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
422 // or along dimension 0 or 2 for a 3-D tensor.
423 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100424 {
narpra01f176d5a2018-11-18 20:17:48 +0000425 concatDimension = 1;
426 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
427 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100428 }
narpra01f176d5a2018-11-18 20:17:48 +0000429 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100430 {
narpra01f176d5a2018-11-18 20:17:48 +0000431 concatDimension = 0;
432 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
433 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100434 }
narpra01f176d5a2018-11-18 20:17:48 +0000435 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100436}
437
438} // anonymous namespace
439
440namespace armnn_driver
441{
442
443//// Creates an ArmNN activation layer and connects it to the given layer, if the
444//// passed in AndroidNN activation function requires so.
445//// @return The end layer of the sequence of layers built for the given AndroidNN
446//// activation function or nullptr if an error occurred (e.g. unsupported activation).
447//// Note that the end layer matches the input layer if no activation is required
448//// (the sequence of layers has length 1).
449armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
450 ActivationFn activation,
451 armnn::IConnectableLayer* prevLayer,
452 ConversionData& data);
453
454} // namespace armnn_driver
455
456///
457/// Utility templates
458///
459
460namespace armnn_driver
461{
462
463using namespace android::nn;
464
465template<typename HalOperation, typename HalModel>
saoste01b8471482018-10-10 09:44:51 +0100466const Operand* GetInputOperand(const HalOperation& operation, uint32_t inputIndex, const HalModel& model,
467 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100468{
469 if (inputIndex >= operation.inputs.size())
470 {
saoste01b8471482018-10-10 09:44:51 +0100471 if (failOnIndexOutOfBounds)
472 {
473 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
474 }
arovir01b0717b52018-09-05 17:03:25 +0100475 return nullptr;
476 }
477
478 BOOST_ASSERT(operation.inputs[inputIndex] < model.operands.size()); // Model should have been validated beforehand
479 return &model.operands[operation.inputs[inputIndex]];
480}
481
482template<typename HalOperation, typename HalModel>
483const Operand* GetOutputOperand(const HalOperation& operation, uint32_t outputIndex, const HalModel& model)
484{
485 if (outputIndex >= operation.outputs.size())
486 {
487 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
488 return nullptr;
489 }
490
491 // Model should have been validated beforehand
492 BOOST_ASSERT(operation.outputs[outputIndex] < model.operands.size());
493
494 return &model.operands[operation.outputs[outputIndex]];
495}
496
497template<typename HalModel>
498ConstTensorPin ConvertOperandToConstTensorPin(const Operand& operand,
499 const HalModel& model,
500 const ConversionData& data,
501 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
502 const armnn::TensorShape* overrideTensorShape = nullptr,
503 bool optional = false)
504{
505 if (!IsOperandTypeSupportedForTensors(operand.type))
506 {
507 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
508 return ConstTensorPin();
509 }
510
Kevin Mayf29a2c52019-03-14 11:56:32 +0000511 if (!optional &&
512 operand.lifetime != OperandLifeTime::CONSTANT_COPY &&
513 operand.lifetime != OperandLifeTime::CONSTANT_REFERENCE &&
514 operand.lifetime != OperandLifeTime::NO_VALUE)
arovir01b0717b52018-09-05 17:03:25 +0100515 {
516 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
517 return ConstTensorPin();
518 }
519
Kevin Mayf29a2c52019-03-14 11:56:32 +0000520 const void* const valueStart = GetOperandValueReadOnlyAddress(operand, model, data, optional);
arovir01b0717b52018-09-05 17:03:25 +0100521 if (!valueStart)
522 {
523 if (optional)
524 {
525 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
526 return ConstTensorPin(true);
527 }
528 // mandatory tensor with no values
529 Fail("%s: failed to get operand address", __func__);
530 return ConstTensorPin();
531 }
532
533 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
534 if (overrideTensorShape != nullptr)
535 {
536 tensorInfo.SetShape(*overrideTensorShape);
537 }
538 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
539}
540
541template<typename HalOperation, typename HalModel>
542ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
543 uint32_t inputIndex,
544 const HalModel& model,
545 const ConversionData& data,
546 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
547 const armnn::TensorShape* overrideTensorShape = nullptr,
548 bool optional = false)
549{
550 const Operand* operand = GetInputOperand(operation, inputIndex, model);
551 if (!operand)
552 {
553 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
554 return ConstTensorPin();
555 }
556 return ConvertOperandToConstTensorPin(*operand,
557 model,
558 data,
559 dimensionMappings,
560 overrideTensorShape,
561 optional);
562}
563
564template<typename HalModel>
Kevin Mayf29a2c52019-03-14 11:56:32 +0000565const void* GetOperandValueReadOnlyAddress(const Operand& operand, const HalModel& model, const ConversionData& data,
566 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100567{
568 const void* valueStart = nullptr;
569
570 switch (operand.lifetime)
571 {
572 case OperandLifeTime::CONSTANT_COPY:
573 {
574 // Constant found in model.operandValues
575 valueStart = &model.operandValues[operand.location.offset];
576 break;
577 }
578 case OperandLifeTime::CONSTANT_REFERENCE:
579 {
580 // Constant specified via a Memory object
581 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
582 break;
583 }
Kevin Mayf29a2c52019-03-14 11:56:32 +0000584 case OperandLifeTime::NO_VALUE:
585 {
586 // An optional input tensor with no values is not an error so should not register as a fail
587 if (optional)
588 {
589 valueStart = nullptr;
590 break;
591 }
592 }
arovir01b0717b52018-09-05 17:03:25 +0100593 default:
594 {
595 // Unsupported/invalid (e.g. can't get value of an input to the model)
596 Fail("%s: unsupported/invalid operand lifetime: %s",
597 __func__, toString(operand.lifetime).c_str());
598 valueStart = nullptr;
599 }
600 }
601
602 return valueStart;
603}
604
605template<typename HalOperation, typename HalModel, typename OutputType>
606bool GetInputScalar(const HalOperation& operation,
607 uint32_t inputIndex,
608 OperandType type,
609 OutputType& outValue,
610 const HalModel& model,
611 const ConversionData& data)
612{
613 const Operand* operand = GetInputOperand(operation, inputIndex, model);
614 if (!operand)
615 {
616 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
617 }
618
619 if (operand->type != type)
620 {
621 return Fail("%s: unexpected operand type: %s (should be %s)",
622 __func__, toString(operand->type).c_str(), toString(type).c_str());
623 }
624
625 if (operand->location.length != sizeof(OutputType))
626 {
627 return Fail("%s: incorrect operand location length: %i (should be %i)",
628 __func__, operand->location.length, sizeof(OutputType));
629 }
630
631 const void* valueAddress = GetOperandValueReadOnlyAddress(*operand, model, data);
632 if (!valueAddress)
633 {
634 return Fail("%s: failed to get address for operand", __func__);
635 }
636
637 outValue = *(static_cast<const OutputType*>(valueAddress));
638 return true;
639}
640
641template<typename HalOperation, typename HalModel>
642bool GetInputInt32(const HalOperation& operation,
643 uint32_t inputIndex,
644 int32_t& outValue,
645 const HalModel& model,
646 const ConversionData& data)
647{
648 return GetInputScalar(operation, inputIndex, OperandType::INT32, outValue, model, data);
649}
650
651
652template<typename HalOperation, typename HalModel>
653bool GetInputFloat32(const HalOperation& operation,
654 uint32_t inputIndex,
655 float& outValue,
656 const HalModel& model,
657 const ConversionData& data)
658{
659 return GetInputScalar(operation, inputIndex, OperandType::FLOAT32, outValue, model, data);
660}
661
662
663template<typename HalOperation, typename HalModel>
664bool GetInputActivationFunctionImpl(const HalOperation& operation,
665 uint32_t inputIndex,
666 OperandType type,
667 ActivationFn& outActivationFunction,
668 const HalModel& model,
669 const ConversionData& data)
670{
671 if (type != OperandType::INT32 && type != OperandType::TENSOR_INT32)
672 {
673 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
674 __func__,
675 toString(type).c_str(),
676 toString(OperandType::INT32).c_str(),
677 toString(OperandType::TENSOR_INT32).c_str());
678 }
679
680 int32_t activationFunctionAsInt;
681 if (!GetInputScalar(operation, inputIndex, type, activationFunctionAsInt, model, data))
682 {
683 return Fail("%s: failed to get activation input value", __func__);
684 }
685 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
686 return true;
687}
688
689
690template<typename HalOperation, typename HalModel>
691bool GetInputActivationFunction(const HalOperation& operation,
692 uint32_t inputIndex,
693 ActivationFn& outActivationFunction,
694 const HalModel& model,
695 const ConversionData& data)
696{
697 return GetInputActivationFunctionImpl(operation,
698 inputIndex,
699 OperandType::INT32,
700 outActivationFunction,
701 model,
702 data);
703}
704
705template<typename HalOperation, typename HalModel>
706bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
707 uint32_t inputIndex,
708 ActivationFn& outActivationFunction,
709 const HalModel& model,
710 const ConversionData& data)
711{
712 // This only accepts a 1-D tensor of size 1
713 return GetInputActivationFunctionImpl(operation,
714 inputIndex,
715 OperandType::INT32,
716 outActivationFunction,
717 model,
718 data);
719}
720
721
722template<typename HalOperation, typename HalModel>
723bool GetOptionalInputActivation(const HalOperation& operation,
724 uint32_t inputIndex,
725 ActivationFn& activationFunction,
726 const HalModel& model,
727 const ConversionData& data)
728{
729 if (operation.inputs.size() <= inputIndex)
730 {
731 activationFunction = ActivationFn::kActivationNone;
732 }
733 else
734 {
735 if (!GetInputActivationFunction(operation, inputIndex, activationFunction, model, data))
736 {
737 return Fail("%s: Operation has invalid inputs", __func__);
738 }
739 }
740 return true;
741}
742
743template<typename HalModel>
744bool GetTensorInt32Values(const Operand& operand,
745 std::vector<int32_t>& outValues,
746 const HalModel& model,
747 const ConversionData& data)
748{
749 if (operand.type != OperandType::TENSOR_INT32)
750 {
751 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
752 }
753
754 const void* startAddress = GetOperandValueReadOnlyAddress(operand, model, data);
755 if (!startAddress)
756 {
757 return Fail("%s: failed to get operand address", __func__, operand.type);
758 }
759
760 // Check number of bytes is sensible
761 const uint32_t numBytes = operand.location.length;
762 if (numBytes % sizeof(int32_t) != 0)
763 {
764 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
765 __func__, numBytes, sizeof(int32_t));
766 }
767
768 outValues.resize(numBytes / sizeof(int32_t));
769 memcpy(outValues.data(), startAddress, numBytes);
770 return true;
771}
772
773template<typename HalOperation, typename HalModel>
774bool GetInputPaddingScheme(const HalOperation& operation,
775 uint32_t inputIndex,
776 PaddingScheme& outPaddingScheme,
777 const HalModel& model,
778 const ConversionData& data)
779{
780 int32_t paddingSchemeAsInt;
781 if (!GetInputInt32(operation, inputIndex, paddingSchemeAsInt, model, data))
782 {
783 return Fail("%s: failed to get padding scheme input value", __func__);
784 }
785
786 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
787 return true;
788}
789
790template<typename HalOperation, typename HalModel>
791LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
792 uint32_t inputIndex,
793 const HalModel& model,
794 ConversionData& data)
795{
796 const Operand* operand = GetInputOperand(operation, inputIndex, model);
797 if (!operand)
798 {
799 Fail("%s: failed to get input operand %i", __func__, inputIndex);
800 return LayerInputHandle();
801 }
802
803 if (!IsOperandTypeSupportedForTensors(operand->type))
804 {
805 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
806 return LayerInputHandle();
807 }
808
809 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
810
811 switch (operand->lifetime)
812 {
813 case OperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
814 case OperandLifeTime::MODEL_INPUT:
Matthew Benthamfecc7792018-10-25 12:44:10 +0100815 case OperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +0100816 {
817 // The tensor is either an operand internal to the model, or a model input.
818 // It can be associated with an ArmNN output slot for an existing layer.
819
820 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
821 const uint32_t operandIndex = operation.inputs[inputIndex];
822 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
823 break;
824 }
825 case OperandLifeTime::CONSTANT_COPY:
826 case OperandLifeTime::CONSTANT_REFERENCE:
827 {
828 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
829 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin(*operand, model, data);
830 if (tensorPin.IsValid())
831 {
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100832 if (!IsLayerSupportedForAnyBackend(__func__,
833 armnn::IsConstantSupported,
834 data.m_Backends,
835 tensorPin.GetConstTensor().GetInfo()))
arovir01b0717b52018-09-05 17:03:25 +0100836 {
837 return LayerInputHandle();
838 }
839
840 armnn::IConnectableLayer* constantLayer = data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
841 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
842 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
843
844 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
845 }
846 else
847 {
848 Fail("%s: invalid operand tensor", __func__);
849 return LayerInputHandle();
850 }
851 break;
852 }
853 default:
854 {
855 // Unsupported lifetime for an input tensor
856 Fail("%s: unsupported lifetime for input tensor: %s",
857 __func__, toString(operand->lifetime).c_str());
858 return LayerInputHandle();
859 }
860 }
861}
862
863template<typename HalOperation, typename HalModel>
864bool ConvertToActivation(const HalOperation& operation,
865 const char* operationName,
866 const armnn::ActivationDescriptor& activationDesc,
867 const HalModel& model,
868 ConversionData& data)
869{
870 LayerInputHandle input = ConvertToLayerInputHandle(operation, 0, model, data);
871 if (!input.IsValid())
872 {
873 return Fail("%s: Input 0 is invalid", operationName);
874 }
875
876 const Operand* outputOperand = GetOutputOperand(operation, 0, model);
877 if (!outputOperand)
878 {
879 return false;
880 }
881 const armnn::TensorInfo outInfo = GetTensorInfoForOperand(*outputOperand);
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100882 if (!IsLayerSupportedForAnyBackend(__func__,
883 armnn::IsActivationSupported,
884 data.m_Backends,
885 input.GetTensorInfo(),
886 outInfo,
887 activationDesc))
arovir01b0717b52018-09-05 17:03:25 +0100888 {
889 return false;
890 }
891
892 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
893 BOOST_ASSERT(layer != nullptr);
894 input.Connect(layer->GetInputSlot(0));
895
896 return SetupAndTrackLayerOutputSlot(operation, 0, *layer, model, data);
897}
898
899template<typename HalOperation, typename HalModel>
900bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
901 uint32_t operationOutputIndex,
902 armnn::IConnectableLayer& layer,
903 uint32_t layerOutputIndex,
904 const HalModel& model,
905 ConversionData& data)
906{
907 const Operand* outputOperand = GetOutputOperand(operation, operationOutputIndex, model);
908 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
909 {
910 return false;
911 }
912
913 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
914
915 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
916 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
917
918 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
919
920 return true;
921}
922
923template<typename HalOperation, typename HalModel>
924bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
925 uint32_t outputIndex,
926 armnn::IConnectableLayer& layer,
927 const HalModel& model,
928 ConversionData& data)
929{
930 return SetupAndTrackLayerOutputSlot(operation, outputIndex, layer, outputIndex, model, data);
931}
932
933template<typename HalOperation, typename HalModel>
934bool ConvertPooling2d(const HalOperation& operation,
935 const char* operationName,
936 armnn::PoolingAlgorithm poolType,
937 const HalModel& model,
938 ConversionData& data)
939{
940 LayerInputHandle input = ConvertToLayerInputHandle(operation, 0, model, data);
941 if (!input.IsValid())
942 {
943 return Fail("%s: Could not read input 0", operationName);
944 }
945
946 const Operand* output = GetOutputOperand(operation, 0, model);
947 if (!output)
948 {
949 return Fail("%s: Could not read output 0", __func__);
950 }
951
952 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
953 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
954
arovir01b0717b52018-09-05 17:03:25 +0100955 armnn::Pooling2dDescriptor desc;
956 desc.m_PoolType = poolType;
957 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +0100958 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +0100959
960 ActivationFn activation;
961
962 if (operation.inputs.size() == 7)
963 {
964 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
965 android::nn::PaddingScheme scheme;
966 if (!GetInputPaddingScheme(operation, 1, scheme, model, data)
967 || !GetInputScalar(operation, 2, OperandType::INT32, desc.m_StrideX, model, data)
968 || !GetInputScalar(operation, 3, OperandType::INT32, desc.m_StrideY, model, data)
969 || !GetInputScalar(operation, 4, OperandType::INT32, desc.m_PoolWidth, model, data)
970 || !GetInputScalar(operation, 5, OperandType::INT32, desc.m_PoolHeight, model, data)
971 || !GetInputActivationFunction(operation, 6, activation, model, data))
972 {
973 return Fail("%s: Operation has invalid inputs", operationName);
974 }
975
Matteo Martincigh39fc5472018-10-26 16:39:28 +0100976 const unsigned int inputWidth = inputInfo.GetShape()[2];
977 const unsigned int inputHeight = inputInfo.GetShape()[1];
arovir01b0717b52018-09-05 17:03:25 +0100978
979 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
980 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
981 }
982 else
983 {
984 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
985 if (!GetInputScalar(operation, 1, OperandType::INT32, desc.m_PadLeft, model, data)
986 || !GetInputScalar(operation, 2, OperandType::INT32, desc.m_PadRight, model, data)
987 || !GetInputScalar(operation, 3, OperandType::INT32, desc.m_PadTop, model, data)
988 || !GetInputScalar(operation, 4, OperandType::INT32, desc.m_PadBottom, model, data)
989 || !GetInputScalar(operation, 5, OperandType::INT32, desc.m_StrideX, model, data)
990 || !GetInputScalar(operation, 6, OperandType::INT32, desc.m_StrideY, model, data)
991 || !GetInputScalar(operation, 7, OperandType::INT32, desc.m_PoolWidth, model, data)
992 || !GetInputScalar(operation, 8, OperandType::INT32, desc.m_PoolHeight, model, data)
993 || !GetInputActivationFunction(operation, 9, activation, model, data))
994 {
995 return Fail("%s: Operation has invalid inputs", operationName);
996 }
997 }
998
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100999 if (!IsLayerSupportedForAnyBackend(__func__,
1000 armnn::IsPooling2dSupported,
1001 data.m_Backends,
1002 inputInfo,
1003 outputInfo,
1004 desc))
arovir01b0717b52018-09-05 17:03:25 +01001005 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001006 return false;
arovir01b0717b52018-09-05 17:03:25 +01001007 }
arovir01b0717b52018-09-05 17:03:25 +01001008
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001009 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1010 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001011 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001012 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001013 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001014
1015 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1016 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001017 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001018 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001019 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001020
1021 input.Connect(pooling2dLayer->GetInputSlot(0));
1022
1023 return SetupAndTrackLayerOutputSlot(operation, 0, *endLayer, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001024}
1025
saoste01b8471482018-10-10 09:44:51 +01001026} // namespace armnn_driver