blob: b2fd5cb79908050d67a5fd86c06d2115b5b43414 [file] [log] [blame]
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01001//
Jim Flynn357add22023-04-10 23:26:40 +01002// Copyright © 2017, 2023 Arm Ltd and Contributors. All rights reserved.
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01003// SPDX-License-Identifier: MIT
4//
5
SiCong Li39f46392019-06-21 12:00:04 +01006#include "../ImageTensorGenerator/ImageTensorGenerator.hpp"
7#include "../InferenceTest.hpp"
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01008#include "ModelAccuracyChecker.hpp"
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01009#include "armnnDeserializer/IDeserializer.hpp"
David Monahan6bb47a72021-10-22 12:57:28 +010010
Rob Hughes9542f902021-07-14 09:48:54 +010011#include <armnnUtils/Filesystem.hpp>
Francis Murtagh40d27412021-10-28 11:11:35 +010012#include <armnnUtils/TContainer.hpp>
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010013
Matthew Sloyane7ba17e2020-10-06 10:03:21 +010014#include <cxxopts/cxxopts.hpp>
SiCong Li39f46392019-06-21 12:00:04 +010015#include <map>
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010016
17using namespace armnn::test;
18
SiCong Li898a3242019-06-24 16:03:33 +010019/** Load image names and ground-truth labels from the image directory and the ground truth label file
20 *
21 * @pre \p validationLabelPath exists and is valid regular file
22 * @pre \p imageDirectoryPath exists and is valid directory
23 * @pre labels in validation file correspond to images which are in lexicographical order with the image name
24 * @pre image index starts at 1
25 * @pre \p begIndex and \p endIndex are end-inclusive
26 *
27 * @param[in] validationLabelPath Path to validation label file
28 * @param[in] imageDirectoryPath Path to directory containing validation images
29 * @param[in] begIndex Begin index of images to be loaded. Inclusive
30 * @param[in] endIndex End index of images to be loaded. Inclusive
Teresa Charlin2b30f162021-11-17 11:46:25 +000031 * @param[in] excludelistPath Path to excludelist file
SiCong Li898a3242019-06-24 16:03:33 +010032 * @return A map mapping image file names to their corresponding ground-truth labels
33 */
34map<std::string, std::string> LoadValidationImageFilenamesAndLabels(const string& validationLabelPath,
35 const string& imageDirectoryPath,
36 size_t begIndex = 0,
37 size_t endIndex = 0,
Teresa Charlin2b30f162021-11-17 11:46:25 +000038 const string& excludelistPath = "");
SiCong Li898a3242019-06-24 16:03:33 +010039
40/** Load model output labels from file
Teresa Charlin2b30f162021-11-17 11:46:25 +000041 *
SiCong Li898a3242019-06-24 16:03:33 +010042 * @pre \p modelOutputLabelsPath exists and is a regular file
43 *
44 * @param[in] modelOutputLabelsPath path to model output labels file
45 * @return A vector of labels, which in turn is described by a list of category names
46 */
47std::vector<armnnUtils::LabelCategoryNames> LoadModelOutputLabels(const std::string& modelOutputLabelsPath);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010048
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010049int main(int argc, char* argv[])
50{
51 try
52 {
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010053 armnn::LogSeverity level = armnn::LogSeverity::Debug;
54 armnn::ConfigureLogging(true, true, level);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010055
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010056 std::string modelPath;
SiCong Li39f46392019-06-21 12:00:04 +010057 std::string modelFormat;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +010058 std::vector<std::string> inputNames;
59 std::vector<std::string> outputNames;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010060 std::string dataDir;
SiCong Li898a3242019-06-24 16:03:33 +010061 std::string modelOutputLabelsPath;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010062 std::string validationLabelPath;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +010063 std::string inputLayout;
64 std::vector<armnn::BackendId> computeDevice;
SiCong Li898a3242019-06-24 16:03:33 +010065 std::string validationRange;
Teresa Charlin2b30f162021-11-17 11:46:25 +000066 std::string excludelistPath;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010067
68 const std::string backendsMessage = "Which device to run layers on by default. Possible choices: "
69 + armnn::BackendRegistryInstance().GetBackendIdsAsString();
70
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010071 try
72 {
Matthew Sloyane7ba17e2020-10-06 10:03:21 +010073 cxxopts::Options options("ModeAccuracyTool-Armnn","Options");
74
75 options.add_options()
76 ("h,help", "Display help messages")
77 ("m,model-path",
78 "Path to armnn format model file",
79 cxxopts::value<std::string>(modelPath))
80 ("f,model-format",
Nikhil Raj5d955cf2021-04-19 16:59:48 +010081 "The model format. Supported values: tflite",
Matthew Sloyane7ba17e2020-10-06 10:03:21 +010082 cxxopts::value<std::string>(modelFormat))
83 ("i,input-name",
84 "Identifier of the input tensors in the network separated by comma with no space.",
85 cxxopts::value<std::vector<std::string>>(inputNames))
86 ("o,output-name",
87 "Identifier of the output tensors in the network separated by comma with no space.",
88 cxxopts::value<std::vector<std::string>>(outputNames))
89 ("d,data-dir",
90 "Path to directory containing the ImageNet test data",
91 cxxopts::value<std::string>(dataDir))
92 ("p,model-output-labels",
93 "Path to model output labels file.",
94 cxxopts::value<std::string>(modelOutputLabelsPath))
95 ("v,validation-labels-path",
96 "Path to ImageNet Validation Label file",
97 cxxopts::value<std::string>(validationLabelPath))
98 ("l,data-layout",
99 "Data layout. Supported value: NHWC, NCHW. Default: NHWC",
100 cxxopts::value<std::string>(inputLayout)->default_value("NHWC"))
101 ("c,compute",
102 backendsMessage.c_str(),
103 cxxopts::value<std::vector<armnn::BackendId>>(computeDevice)->default_value("CpuAcc,CpuRef"))
104 ("r,validation-range",
105 "The range of the images to be evaluated. Specified in the form <begin index>:<end index>."
106 "The index starts at 1 and the range is inclusive."
107 "By default the evaluation will be performed on all images.",
108 cxxopts::value<std::string>(validationRange)->default_value("1:0"))
Teresa Charlin2b30f162021-11-17 11:46:25 +0000109 ("e,excludelist-path",
110 "Path to a excludelist file where each line denotes the index of an image to be "
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100111 "excluded from evaluation.",
Teresa Charlin2b30f162021-11-17 11:46:25 +0000112 cxxopts::value<std::string>(excludelistPath)->default_value(""));
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100113
114 auto result = options.parse(argc, argv);
115
116 if (result.count("help") > 0)
117 {
118 std::cout << options.help() << std::endl;
119 return EXIT_FAILURE;
120 }
121
122 // Check for mandatory single options.
123 std::string mandatorySingleParameters[] = { "model-path", "model-format", "input-name", "output-name",
124 "data-dir", "model-output-labels", "validation-labels-path" };
125 for (auto param : mandatorySingleParameters)
126 {
127 if (result.count(param) != 1)
128 {
129 std::cerr << "Parameter \'--" << param << "\' is required but missing." << std::endl;
130 return EXIT_FAILURE;
131 }
132 }
133 }
Jim Flynn357add22023-04-10 23:26:40 +0100134 catch (const cxxopts::exceptions::exception& e)
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100135 {
136 std::cerr << e.what() << std::endl << std::endl;
137 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100138 }
139 catch (const std::exception& e)
140 {
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100141 ARMNN_ASSERT_MSG(false, "Caught unexpected exception");
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100142 std::cerr << "Fatal internal error: " << e.what() << std::endl;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100143 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100144 }
145
146 // Check if the requested backend are all valid
147 std::string invalidBackends;
148 if (!CheckRequestedBackendsAreValid(computeDevice, armnn::Optional<std::string&>(invalidBackends)))
149 {
Derek Lamberti08446972019-11-26 16:38:31 +0000150 ARMNN_LOG(fatal) << "The list of preferred devices contains invalid backend IDs: "
151 << invalidBackends;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100152 return EXIT_FAILURE;
153 }
154 armnn::Status status;
155
156 // Create runtime
157 armnn::IRuntime::CreationOptions options;
158 armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options));
159 std::ifstream file(modelPath);
160
161 // Create Parser
162 using IParser = armnnDeserializer::IDeserializer;
163 auto armnnparser(IParser::Create());
164
165 // Create a network
166 armnn::INetworkPtr network = armnnparser->CreateNetworkFromBinary(file);
167
168 // Optimizes the network.
169 armnn::IOptimizedNetworkPtr optimizedNet(nullptr, nullptr);
170 try
171 {
172 optimizedNet = armnn::Optimize(*network, computeDevice, runtime->GetDeviceSpec());
173 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000174 catch (const armnn::Exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100175 {
176 std::stringstream message;
177 message << "armnn::Exception (" << e.what() << ") caught from optimize.";
Derek Lamberti08446972019-11-26 16:38:31 +0000178 ARMNN_LOG(fatal) << message.str();
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100179 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100180 }
181
182 // Loads the network into the runtime.
183 armnn::NetworkId networkId;
184 status = runtime->LoadNetwork(networkId, std::move(optimizedNet));
185 if (status == armnn::Status::Failure)
186 {
Derek Lamberti08446972019-11-26 16:38:31 +0000187 ARMNN_LOG(fatal) << "armnn::IRuntime: Failed to load network";
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100188 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100189 }
190
191 // Set up Network
192 using BindingPointInfo = InferenceModelInternal::BindingPointInfo;
193
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100194 // Handle inputNames and outputNames, there can be multiple.
195 std::vector<BindingPointInfo> inputBindings;
196 for(auto& input: inputNames)
197 {
198 const armnnDeserializer::BindingPointInfo&
199 inputBindingInfo = armnnparser->GetNetworkInputBindingInfo(0, input);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100200
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100201 std::pair<armnn::LayerBindingId, armnn::TensorInfo>
202 m_InputBindingInfo(inputBindingInfo.m_BindingId, inputBindingInfo.m_TensorInfo);
203 inputBindings.push_back(m_InputBindingInfo);
204 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100205
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100206 std::vector<BindingPointInfo> outputBindings;
207 for(auto& output: outputNames)
208 {
209 const armnnDeserializer::BindingPointInfo&
210 outputBindingInfo = armnnparser->GetNetworkOutputBindingInfo(0, output);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100211
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100212 std::pair<armnn::LayerBindingId, armnn::TensorInfo>
213 m_OutputBindingInfo(outputBindingInfo.m_BindingId, outputBindingInfo.m_TensorInfo);
214 outputBindings.push_back(m_OutputBindingInfo);
215 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100216
SiCong Li898a3242019-06-24 16:03:33 +0100217 // Load model output labels
Francis Murtagh532a29d2020-06-29 11:50:01 +0100218 if (modelOutputLabelsPath.empty() || !fs::exists(modelOutputLabelsPath) ||
219 !fs::is_regular_file(modelOutputLabelsPath))
SiCong Li898a3242019-06-24 16:03:33 +0100220 {
Derek Lamberti08446972019-11-26 16:38:31 +0000221 ARMNN_LOG(fatal) << "Invalid model output labels path at " << modelOutputLabelsPath;
SiCong Li898a3242019-06-24 16:03:33 +0100222 }
223 const std::vector<armnnUtils::LabelCategoryNames> modelOutputLabels =
224 LoadModelOutputLabels(modelOutputLabelsPath);
225
226 // Parse begin and end image indices
227 std::vector<std::string> imageIndexStrs = armnnUtils::SplitBy(validationRange, ":");
228 size_t imageBegIndex;
229 size_t imageEndIndex;
230 if (imageIndexStrs.size() != 2)
231 {
Derek Lamberti08446972019-11-26 16:38:31 +0000232 ARMNN_LOG(fatal) << "Invalid validation range specification: Invalid format " << validationRange;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100233 return EXIT_FAILURE;
SiCong Li898a3242019-06-24 16:03:33 +0100234 }
235 try
236 {
237 imageBegIndex = std::stoul(imageIndexStrs[0]);
238 imageEndIndex = std::stoul(imageIndexStrs[1]);
239 }
240 catch (const std::exception& e)
241 {
Derek Lamberti08446972019-11-26 16:38:31 +0000242 ARMNN_LOG(fatal) << "Invalid validation range specification: " << validationRange;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100243 return EXIT_FAILURE;
SiCong Li898a3242019-06-24 16:03:33 +0100244 }
245
Teresa Charlin2b30f162021-11-17 11:46:25 +0000246 // Validate excludelist file if it's specified
247 if (!excludelistPath.empty() &&
248 !(fs::exists(excludelistPath) && fs::is_regular_file(excludelistPath)))
SiCong Li898a3242019-06-24 16:03:33 +0100249 {
Teresa Charlin2b30f162021-11-17 11:46:25 +0000250 ARMNN_LOG(fatal) << "Invalid path to excludelist file at " << excludelistPath;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100251 return EXIT_FAILURE;
SiCong Li898a3242019-06-24 16:03:33 +0100252 }
253
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100254 fs::path pathToDataDir(dataDir);
SiCong Li898a3242019-06-24 16:03:33 +0100255 const map<std::string, std::string> imageNameToLabel = LoadValidationImageFilenamesAndLabels(
Teresa Charlin2b30f162021-11-17 11:46:25 +0000256 validationLabelPath, pathToDataDir.string(), imageBegIndex, imageEndIndex, excludelistPath);
SiCong Li898a3242019-06-24 16:03:33 +0100257 armnnUtils::ModelAccuracyChecker checker(imageNameToLabel, modelOutputLabels);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100258
SiCong Li39f46392019-06-21 12:00:04 +0100259 if (ValidateDirectory(dataDir))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100260 {
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100261 InferenceModel<armnnDeserializer::IDeserializer, float>::Params params;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100262
SiCong Li39f46392019-06-21 12:00:04 +0100263 params.m_ModelPath = modelPath;
264 params.m_IsModelBinary = true;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100265 params.m_ComputeDevices = computeDevice;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100266 // Insert inputNames and outputNames into params vector
267 params.m_InputBindings.insert(std::end(params.m_InputBindings),
268 std::begin(inputNames),
269 std::end(inputNames));
270 params.m_OutputBindings.insert(std::end(params.m_OutputBindings),
271 std::begin(outputNames),
272 std::end(outputNames));
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100273
274 using TParser = armnnDeserializer::IDeserializer;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100275 // If dynamicBackends is empty it will be disabled by default.
276 InferenceModel<TParser, float> model(params, false, "");
277
SiCong Li39f46392019-06-21 12:00:04 +0100278 // Get input tensor information
279 const armnn::TensorInfo& inputTensorInfo = model.GetInputBindingInfo().second;
280 const armnn::TensorShape& inputTensorShape = inputTensorInfo.GetShape();
281 const armnn::DataType& inputTensorDataType = inputTensorInfo.GetDataType();
282 armnn::DataLayout inputTensorDataLayout;
283 if (inputLayout == "NCHW")
284 {
285 inputTensorDataLayout = armnn::DataLayout::NCHW;
286 }
287 else if (inputLayout == "NHWC")
288 {
289 inputTensorDataLayout = armnn::DataLayout::NHWC;
290 }
291 else
292 {
Derek Lamberti08446972019-11-26 16:38:31 +0000293 ARMNN_LOG(fatal) << "Invalid Data layout: " << inputLayout;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100294 return EXIT_FAILURE;
SiCong Li39f46392019-06-21 12:00:04 +0100295 }
296 const unsigned int inputTensorWidth =
297 inputTensorDataLayout == armnn::DataLayout::NCHW ? inputTensorShape[3] : inputTensorShape[2];
298 const unsigned int inputTensorHeight =
299 inputTensorDataLayout == armnn::DataLayout::NCHW ? inputTensorShape[2] : inputTensorShape[1];
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100300 // Get output tensor info
301 const unsigned int outputNumElements = model.GetOutputSize();
SiCong Li898a3242019-06-24 16:03:33 +0100302 // Check output tensor shape is valid
303 if (modelOutputLabels.size() != outputNumElements)
304 {
Derek Lamberti08446972019-11-26 16:38:31 +0000305 ARMNN_LOG(fatal) << "Number of output elements: " << outputNumElements
SiCong Li898a3242019-06-24 16:03:33 +0100306 << " , mismatches the number of output labels: " << modelOutputLabels.size();
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100307 return EXIT_FAILURE;
SiCong Li898a3242019-06-24 16:03:33 +0100308 }
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100309
SiCong Li39f46392019-06-21 12:00:04 +0100310 const unsigned int batchSize = 1;
311 // Get normalisation parameters
312 SupportedFrontend modelFrontend;
Nikhil Raj5d955cf2021-04-19 16:59:48 +0100313 if (modelFormat == "tflite")
SiCong Li39f46392019-06-21 12:00:04 +0100314 {
315 modelFrontend = SupportedFrontend::TFLite;
316 }
317 else
318 {
Derek Lamberti08446972019-11-26 16:38:31 +0000319 ARMNN_LOG(fatal) << "Unsupported frontend: " << modelFormat;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100320 return EXIT_FAILURE;
SiCong Li39f46392019-06-21 12:00:04 +0100321 }
322 const NormalizationParameters& normParams = GetNormalizationParameters(modelFrontend, inputTensorDataType);
SiCong Li898a3242019-06-24 16:03:33 +0100323 for (const auto& imageEntry : imageNameToLabel)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100324 {
SiCong Li898a3242019-06-24 16:03:33 +0100325 const std::string imageName = imageEntry.first;
326 std::cout << "Processing image: " << imageName << "\n";
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100327
Francis Murtagh40d27412021-10-28 11:11:35 +0100328 vector<armnnUtils::TContainer> inputDataContainers;
329 vector<armnnUtils::TContainer> outputDataContainers;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100330
Francis Murtagh532a29d2020-06-29 11:50:01 +0100331 auto imagePath = pathToDataDir / fs::path(imageName);
SiCong Li39f46392019-06-21 12:00:04 +0100332 switch (inputTensorDataType)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100333 {
SiCong Li39f46392019-06-21 12:00:04 +0100334 case armnn::DataType::Signed32:
335 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100336 PrepareImageTensor<int>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100337 inputTensorWidth, inputTensorHeight,
338 normParams,
339 batchSize,
340 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100341 outputDataContainers = { vector<int>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100342 break;
Derek Lambertif90c56d2020-01-10 17:14:08 +0000343 case armnn::DataType::QAsymmU8:
SiCong Li39f46392019-06-21 12:00:04 +0100344 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100345 PrepareImageTensor<uint8_t>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100346 inputTensorWidth, inputTensorHeight,
347 normParams,
348 batchSize,
349 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100350 outputDataContainers = { vector<uint8_t>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100351 break;
352 case armnn::DataType::Float32:
353 default:
354 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100355 PrepareImageTensor<float>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100356 inputTensorWidth, inputTensorHeight,
357 normParams,
358 batchSize,
359 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100360 outputDataContainers = { vector<float>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100361 break;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100362 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100363
364 status = runtime->EnqueueWorkload(networkId,
365 armnnUtils::MakeInputTensors(inputBindings, inputDataContainers),
366 armnnUtils::MakeOutputTensors(outputBindings, outputDataContainers));
367
368 if (status == armnn::Status::Failure)
369 {
Derek Lamberti08446972019-11-26 16:38:31 +0000370 ARMNN_LOG(fatal) << "armnn::IRuntime: Failed to enqueue workload for image: " << imageName;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100371 }
372
Francis Murtagh40d27412021-10-28 11:11:35 +0100373 checker.AddImageResult<armnnUtils::TContainer>(imageName, outputDataContainers);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100374 }
375 }
376 else
377 {
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100378 return EXIT_SUCCESS;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100379 }
380
381 for(unsigned int i = 1; i <= 5; ++i)
382 {
383 std::cout << "Top " << i << " Accuracy: " << checker.GetAccuracy(i) << "%" << "\n";
384 }
385
Derek Lamberti08446972019-11-26 16:38:31 +0000386 ARMNN_LOG(info) << "Accuracy Tool ran successfully!";
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100387 return EXIT_SUCCESS;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100388 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000389 catch (const armnn::Exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100390 {
391 // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
392 // exception of type std::length_error.
393 // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
394 std::cerr << "Armnn Error: " << e.what() << std::endl;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100395 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100396 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000397 catch (const std::exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100398 {
399 // Coverity fix: various boost exceptions can be thrown by methods called by this test.
400 std::cerr << "WARNING: ModelAccuracyTool-Armnn: An error has occurred when running the "
401 "Accuracy Tool: " << e.what() << std::endl;
Matthew Sloyane7ba17e2020-10-06 10:03:21 +0100402 return EXIT_FAILURE;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100403 }
404}
405
SiCong Li898a3242019-06-24 16:03:33 +0100406map<std::string, std::string> LoadValidationImageFilenamesAndLabels(const string& validationLabelPath,
407 const string& imageDirectoryPath,
408 size_t begIndex,
409 size_t endIndex,
Teresa Charlin2b30f162021-11-17 11:46:25 +0000410 const string& excludelistPath)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100411{
SiCong Li898a3242019-06-24 16:03:33 +0100412 // Populate imageFilenames with names of all .JPEG, .PNG images
413 std::vector<std::string> imageFilenames;
Matthew Sloyan2b428032020-10-06 10:45:32 +0100414 for (const auto& imageEntry : fs::directory_iterator(fs::path(imageDirectoryPath)))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100415 {
Francis Murtagh532a29d2020-06-29 11:50:01 +0100416 fs::path imagePath = imageEntry.path();
Matthew Sloyan2b428032020-10-06 10:45:32 +0100417
418 // Get extension and convert to uppercase
419 std::string imageExtension = imagePath.extension().string();
420 std::transform(imageExtension.begin(), imageExtension.end(), imageExtension.begin(), ::toupper);
421
Francis Murtagh532a29d2020-06-29 11:50:01 +0100422 if (fs::is_regular_file(imagePath) && (imageExtension == ".JPEG" || imageExtension == ".PNG"))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100423 {
SiCong Li898a3242019-06-24 16:03:33 +0100424 imageFilenames.push_back(imagePath.filename().string());
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100425 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100426 }
SiCong Li898a3242019-06-24 16:03:33 +0100427 if (imageFilenames.empty())
428 {
429 throw armnn::Exception("No image file (JPEG, PNG) found at " + imageDirectoryPath);
430 }
431
432 // Sort the image filenames lexicographically
433 std::sort(imageFilenames.begin(), imageFilenames.end());
434
435 std::cout << imageFilenames.size() << " images found at " << imageDirectoryPath << std::endl;
436
437 // Get default end index
438 if (begIndex < 1 || endIndex > imageFilenames.size())
439 {
440 throw armnn::Exception("Invalid image index range");
441 }
442 endIndex = endIndex == 0 ? imageFilenames.size() : endIndex;
443 if (begIndex > endIndex)
444 {
445 throw armnn::Exception("Invalid image index range");
446 }
447
Teresa Charlin2b30f162021-11-17 11:46:25 +0000448 // Load excludelist if there is one
449 std::vector<unsigned int> excludelist;
450 if (!excludelistPath.empty())
SiCong Li898a3242019-06-24 16:03:33 +0100451 {
Teresa Charlin2b30f162021-11-17 11:46:25 +0000452 std::ifstream excludelistFile(excludelistPath);
SiCong Li898a3242019-06-24 16:03:33 +0100453 unsigned int index;
Teresa Charlin2b30f162021-11-17 11:46:25 +0000454 while (excludelistFile >> index)
SiCong Li898a3242019-06-24 16:03:33 +0100455 {
Teresa Charlin2b30f162021-11-17 11:46:25 +0000456 excludelist.push_back(index);
SiCong Li898a3242019-06-24 16:03:33 +0100457 }
458 }
459
460 // Load ground truth labels and pair them with corresponding image names
461 std::string classification;
462 map<std::string, std::string> imageNameToLabel;
463 ifstream infile(validationLabelPath);
464 size_t imageIndex = begIndex;
Teresa Charlin2b30f162021-11-17 11:46:25 +0000465 size_t excludelistIndexCount = 0;
SiCong Li898a3242019-06-24 16:03:33 +0100466 while (std::getline(infile, classification))
467 {
468 if (imageIndex > endIndex)
469 {
470 break;
471 }
Teresa Charlin2b30f162021-11-17 11:46:25 +0000472 // If current imageIndex is included in excludelist, skip the current image
473 if (excludelistIndexCount < excludelist.size() && imageIndex == excludelist[excludelistIndexCount])
SiCong Li898a3242019-06-24 16:03:33 +0100474 {
475 ++imageIndex;
Teresa Charlin2b30f162021-11-17 11:46:25 +0000476 ++excludelistIndexCount;
SiCong Li898a3242019-06-24 16:03:33 +0100477 continue;
478 }
479 imageNameToLabel.insert(std::pair<std::string, std::string>(imageFilenames[imageIndex - 1], classification));
480 ++imageIndex;
481 }
Teresa Charlin2b30f162021-11-17 11:46:25 +0000482 std::cout << excludelistIndexCount << " images in excludelist" << std::endl;
483 std::cout << imageIndex - begIndex - excludelistIndexCount << " images to be loaded" << std::endl;
SiCong Li898a3242019-06-24 16:03:33 +0100484 return imageNameToLabel;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100485}
SiCong Li898a3242019-06-24 16:03:33 +0100486
487std::vector<armnnUtils::LabelCategoryNames> LoadModelOutputLabels(const std::string& modelOutputLabelsPath)
488{
489 std::vector<armnnUtils::LabelCategoryNames> modelOutputLabels;
490 ifstream modelOutputLablesFile(modelOutputLabelsPath);
491 std::string line;
492 while (std::getline(modelOutputLablesFile, line))
493 {
494 armnnUtils::LabelCategoryNames tokens = armnnUtils::SplitBy(line, ":");
495 armnnUtils::LabelCategoryNames predictionCategoryNames = armnnUtils::SplitBy(tokens.back(), ",");
496 std::transform(predictionCategoryNames.begin(), predictionCategoryNames.end(), predictionCategoryNames.begin(),
497 [](const std::string& category) { return armnnUtils::Strip(category); });
498 modelOutputLabels.push_back(predictionCategoryNames);
499 }
500 return modelOutputLabels;
Jim Flynn357add22023-04-10 23:26:40 +0100501}