1 //
2 // Copyright © 2017-2018,2020-2021,2023 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5
6 #include "ElementwiseBaseLayer.hpp"
7
8 #include "InternalTypes.hpp"
9 #include "armnn/Exceptions.hpp"
10 #include <armnn/TypesUtils.hpp>
11 #include <armnn/utility/Assert.hpp>
12
13 namespace armnn
14 {
15
ElementwiseBaseLayer(unsigned int numInputSlots,unsigned int numOutputSlots,LayerType type,const char * name)16 ElementwiseBaseLayer::ElementwiseBaseLayer(unsigned int numInputSlots,
17 unsigned int numOutputSlots,
18 LayerType type,
19 const char* name)
20 : Layer(numInputSlots, numOutputSlots, type, name)
21 {}
22
InferOutputShapes(const std::vector<TensorShape> & inputShapes) const23 std::vector<TensorShape> ElementwiseBaseLayer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const
24 {
25 ARMNN_ASSERT(inputShapes.size() == 2);
26 TensorShape input0 = inputShapes[0];
27 TensorShape input1 = inputShapes[1];
28
29 if (inputShapes[0].GetNumDimensions() < inputShapes[1].GetNumDimensions())
30 {
31 input1 = inputShapes[0];
32 input0 = inputShapes[1];
33 }
34
35 unsigned int numDims = input0.GetNumDimensions();
36 unsigned int shiftedDims = input0.GetNumDimensions() - input1.GetNumDimensions();
37
38 // Get the max of the inputs.
39 std::vector<unsigned int> dims(numDims);
40 for (unsigned int i = shiftedDims; i < numDims; i++)
41 {
42 unsigned int dim0 = input0[i];
43 unsigned int dim1 = input1[i - shiftedDims];
44
45 // Validate inputs are broadcast compatible.
46 ARMNN_ASSERT_MSG(dim0 == dim1 || dim0 == 1 || dim1 == 1,
47 "Dimensions should either match or one should be of size 1.");
48
49 dims[i] = std::max(dim0, dim1);
50 }
51
52 // Fill in the rest of the shifted dimensions.
53 for (unsigned int i = 0; i < shiftedDims; i++)
54 {
55 dims[i] = input0[i];
56 }
57
58 return std::vector<TensorShape>({ TensorShape(numDims, dims.data()) });
59 }
60
ValidateTensorShapesFromInputs()61 void ElementwiseBaseLayer::ValidateTensorShapesFromInputs()
62 {
63 VerifyLayerConnections(2, CHECK_LOCATION());
64
65 const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape();
66
67 VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod);
68
69 auto inferredShapes = InferOutputShapes({ GetInputSlot(0).GetConnection()->GetTensorInfo().GetShape(),
70 GetInputSlot(1).GetConnection()->GetTensorInfo().GetShape() });
71
72 ARMNN_ASSERT(inferredShapes.size() == 1);
73
74 ValidateAndCopyShape(outputShape, inferredShapes[0], m_ShapeInferenceMethod, GetLayerTypeAsCString(GetType()));
75 }
76
ExecuteStrategy(IStrategy & strategy) const77 void ElementwiseBaseLayer::ExecuteStrategy(IStrategy& strategy) const
78 {
79 strategy.ExecuteStrategy(this, BaseDescriptor(), {}, GetName());
80 }
81
82 } // namespace armnn
83