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