blob: 96cc1d01847a061892b57d2f187fa5e10dd65806 [file] [log] [blame]
Éanna Ó Catháinc6ab02a2021-04-07 14:35:25 +01001//
2// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7
8#include "Types.hpp"
9
10#include "armnn/ArmNN.hpp"
11#include "armnnTfLiteParser/ITfLiteParser.hpp"
12#include "armnnUtils/DataLayoutIndexed.hpp"
13#include <armnn/Logging.hpp>
14
15#include <string>
16#include <vector>
17
18namespace common
19{
20/**
21* @brief Used to load in a network through ArmNN and run inference on it against a given backend.
22*
23*/
24template <class Tout>
25class ArmnnNetworkExecutor
26{
27private:
28 armnn::IRuntimePtr m_Runtime;
29 armnn::NetworkId m_NetId{};
30 mutable InferenceResults<Tout> m_OutputBuffer;
31 armnn::InputTensors m_InputTensors;
32 armnn::OutputTensors m_OutputTensors;
33 std::vector<armnnTfLiteParser::BindingPointInfo> m_outputBindingInfo;
34
35 std::vector<std::string> m_outputLayerNamesList;
36
37 armnnTfLiteParser::BindingPointInfo m_inputBindingInfo;
38
39 void PrepareTensors(const void* inputData, const size_t dataBytes);
40
41 template <typename Enumeration>
42 auto log_as_int(Enumeration value)
43 -> typename std::underlying_type<Enumeration>::type
44 {
45 return static_cast<typename std::underlying_type<Enumeration>::type>(value);
46 }
47
48public:
49 ArmnnNetworkExecutor() = delete;
50
51 /**
52 * @brief Initializes the network with the given input data. Parsed through TfLiteParser and optimized for a
53 * given backend.
54 *
55 * Note that the output layers names order in m_outputLayerNamesList affects the order of the feature vectors
56 * in output of the Run method.
57 *
58 * * @param[in] modelPath - Relative path to the model file
59 * * @param[in] backends - The list of preferred backends to run inference on
60 */
61 ArmnnNetworkExecutor(std::string& modelPath,
62 std::vector<armnn::BackendId>& backends);
63
64 /**
65 * @brief Returns the aspect ratio of the associated model in the order of width, height.
66 */
67 Size GetImageAspectRatio();
68
69 armnn::DataType GetInputDataType() const;
70
71 float GetQuantizationScale();
72
73 int GetQuantizationOffset();
74
75 /**
76 * @brief Runs inference on the provided input data, and stores the results in the provided InferenceResults object.
77 *
78 * @param[in] inputData - input frame data
79 * @param[in] dataBytes - input data size in bytes
80 * @param[out] results - Vector of DetectionResult objects used to store the output result.
81 */
82 bool Run(const void* inputData, const size_t dataBytes, common::InferenceResults<Tout>& outResults);
83
84};
85
86template <class Tout>
87ArmnnNetworkExecutor<Tout>::ArmnnNetworkExecutor(std::string& modelPath,
88 std::vector<armnn::BackendId>& preferredBackends)
89 : m_Runtime(armnn::IRuntime::Create(armnn::IRuntime::CreationOptions()))
90{
91 // Import the TensorFlow lite model.
92 armnnTfLiteParser::ITfLiteParserPtr parser = armnnTfLiteParser::ITfLiteParser::Create();
93 armnn::INetworkPtr network = parser->CreateNetworkFromBinaryFile(modelPath.c_str());
94
95 std::vector<std::string> inputNames = parser->GetSubgraphInputTensorNames(0);
96
97 m_inputBindingInfo = parser->GetNetworkInputBindingInfo(0, inputNames[0]);
98
99 m_outputLayerNamesList = parser->GetSubgraphOutputTensorNames(0);
100
101 std::vector<armnn::BindingPointInfo> outputBindings;
102 for(const std::string& name : m_outputLayerNamesList)
103 {
104 m_outputBindingInfo.push_back(std::move(parser->GetNetworkOutputBindingInfo(0, name)));
105 }
106 std::vector<std::string> errorMessages;
107 // optimize the network.
108 armnn::IOptimizedNetworkPtr optNet = Optimize(*network,
109 preferredBackends,
110 m_Runtime->GetDeviceSpec(),
111 armnn::OptimizerOptions(),
112 armnn::Optional<std::vector<std::string>&>(errorMessages));
113
114 if (!optNet)
115 {
116 const std::string errorMessage{"ArmnnNetworkExecutor: Failed to optimize network"};
117 ARMNN_LOG(error) << errorMessage;
118 throw armnn::Exception(errorMessage);
119 }
120
121 // Load the optimized network onto the m_Runtime device
122 std::string errorMessage;
123 if (armnn::Status::Success != m_Runtime->LoadNetwork(m_NetId, std::move(optNet), errorMessage))
124 {
125 ARMNN_LOG(error) << errorMessage;
126 throw armnn::Exception(errorMessage);
127 }
128
129 //pre-allocate memory for output (the size of it never changes)
130 for (int it = 0; it < m_outputLayerNamesList.size(); ++it)
131 {
132 const armnn::DataType dataType = m_outputBindingInfo[it].second.GetDataType();
133 const armnn::TensorShape& tensorShape = m_outputBindingInfo[it].second.GetShape();
134
135 std::vector<Tout> oneLayerOutResult;
136 oneLayerOutResult.resize(tensorShape.GetNumElements(), 0);
137 m_OutputBuffer.emplace_back(oneLayerOutResult);
138
139 // Make ArmNN output tensors
140 m_OutputTensors.reserve(m_OutputBuffer.size());
141 for (size_t it = 0; it < m_OutputBuffer.size(); ++it)
142 {
143 m_OutputTensors.emplace_back(std::make_pair(
144 m_outputBindingInfo[it].first,
145 armnn::Tensor(m_outputBindingInfo[it].second,
146 m_OutputBuffer.at(it).data())
147 ));
148 }
149 }
150
151}
152
153template <class Tout>
154armnn::DataType ArmnnNetworkExecutor<Tout>::GetInputDataType() const
155{
156 return m_inputBindingInfo.second.GetDataType();
157}
158
159template <class Tout>
160void ArmnnNetworkExecutor<Tout>::PrepareTensors(const void* inputData, const size_t dataBytes)
161{
162 assert(m_inputBindingInfo.second.GetNumBytes() >= dataBytes);
163 m_InputTensors.clear();
164 m_InputTensors = {{ m_inputBindingInfo.first, armnn::ConstTensor(m_inputBindingInfo.second, inputData)}};
165}
166
167template <class Tout>
168bool ArmnnNetworkExecutor<Tout>::Run(const void* inputData, const size_t dataBytes, InferenceResults<Tout>& outResults)
169{
170 /* Prepare tensors if they are not ready */
171 ARMNN_LOG(debug) << "Preparing tensors...";
172 this->PrepareTensors(inputData, dataBytes);
173 ARMNN_LOG(trace) << "Running inference...";
174
175 armnn::Status ret = m_Runtime->EnqueueWorkload(m_NetId, m_InputTensors, m_OutputTensors);
176
177 std::stringstream inferenceFinished;
178 inferenceFinished << "Inference finished with code {" << log_as_int(ret) << "}\n";
179
180 ARMNN_LOG(trace) << inferenceFinished.str();
181
182 if (ret == armnn::Status::Failure)
183 {
184 ARMNN_LOG(error) << "Failed to perform inference.";
185 }
186
187 outResults.reserve(m_outputLayerNamesList.size());
188 outResults = m_OutputBuffer;
189
190 return (armnn::Status::Success == ret);
191}
192
193template <class Tout>
194float ArmnnNetworkExecutor<Tout>::GetQuantizationScale()
195{
196 return this->m_inputBindingInfo.second.GetQuantizationScale();
197}
198
199template <class Tout>
200int ArmnnNetworkExecutor<Tout>::GetQuantizationOffset()
201{
202 return this->m_inputBindingInfo.second.GetQuantizationOffset();
203}
204
205template <class Tout>
206Size ArmnnNetworkExecutor<Tout>::GetImageAspectRatio()
207{
208 const auto shape = m_inputBindingInfo.second.GetShape();
209 assert(shape.GetNumDimensions() == 4);
210 armnnUtils::DataLayoutIndexed nhwc(armnn::DataLayout::NHWC);
211 return Size(shape[nhwc.GetWidthIndex()],
212 shape[nhwc.GetHeightIndex()]);
213}
214}// namespace common