blob: 8ce7357962b9f1adfc69c3b944e6f556c32dc86d [file] [log] [blame]
Derek Lambertid6cb30e2020-04-28 13:31:29 +01001//
2// Copyright © 2020 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
Jan Eilerse7cc7c32020-06-25 13:18:47 +01005
Derek Lambertid6cb30e2020-04-28 13:31:29 +01006#include "armnnTfLiteParser/ITfLiteParser.hpp"
7
8#include "NMS.hpp"
9
10#include <stb/stb_image.h>
11
12#include <armnn/INetwork.hpp>
13#include <armnn/IRuntime.hpp>
14#include <armnn/Logging.hpp>
15#include <armnn/utility/IgnoreUnused.hpp>
16
Jan Eilerse7cc7c32020-06-25 13:18:47 +010017#include <cxxopts/cxxopts.hpp>
18#include <ghc/filesystem.hpp>
19
Derek Lambertid6cb30e2020-04-28 13:31:29 +010020#include <chrono>
Derek Lambertid6cb30e2020-04-28 13:31:29 +010021#include <fstream>
Jan Eilerse7cc7c32020-06-25 13:18:47 +010022#include <iostream>
Keith Mok16fb1a22021-03-19 08:58:44 -070023#include <cmath>
Derek Lambertid6cb30e2020-04-28 13:31:29 +010024
25using namespace armnnTfLiteParser;
26using namespace armnn;
27
28static const int OPEN_FILE_ERROR = -2;
29static const int OPTIMIZE_NETWORK_ERROR = -3;
30static const int LOAD_NETWORK_ERROR = -4;
31static const int LOAD_IMAGE_ERROR = -5;
32static const int GENERAL_ERROR = -100;
33
Pavel Macenauer855a47b2020-05-26 10:54:22 +000034#define CHECK_OK(v) \
35 do { \
36 try { \
37 auto r_local = v; \
38 if (r_local != 0) { return r_local;} \
39 } \
40 catch (const armnn::Exception& e) \
41 { \
42 ARMNN_LOG(error) << "Oops: " << e.what(); \
43 return GENERAL_ERROR; \
44 } \
Derek Lambertid6cb30e2020-04-28 13:31:29 +010045 } while(0)
46
47
48
49template<typename TContainer>
50inline armnn::InputTensors MakeInputTensors(const std::vector<armnn::BindingPointInfo>& inputBindings,
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +010051 const std::vector<std::reference_wrapper<TContainer>>& inputDataContainers)
Derek Lambertid6cb30e2020-04-28 13:31:29 +010052{
53 armnn::InputTensors inputTensors;
54
55 const size_t numInputs = inputBindings.size();
56 if (numInputs != inputDataContainers.size())
57 {
58 throw armnn::Exception("Mismatching vectors");
59 }
60
61 for (size_t i = 0; i < numInputs; i++)
62 {
63 const armnn::BindingPointInfo& inputBinding = inputBindings[i];
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +010064 const TContainer& inputData = inputDataContainers[i].get();
Derek Lambertid6cb30e2020-04-28 13:31:29 +010065
66 armnn::ConstTensor inputTensor(inputBinding.second, inputData.data());
67 inputTensors.push_back(std::make_pair(inputBinding.first, inputTensor));
68 }
69
70 return inputTensors;
71}
72
73template<typename TContainer>
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +010074inline armnn::OutputTensors MakeOutputTensors(
75 const std::vector<armnn::BindingPointInfo>& outputBindings,
76 const std::vector<std::reference_wrapper<TContainer>>& outputDataContainers)
Derek Lambertid6cb30e2020-04-28 13:31:29 +010077{
78 armnn::OutputTensors outputTensors;
79
80 const size_t numOutputs = outputBindings.size();
81 if (numOutputs != outputDataContainers.size())
82 {
83 throw armnn::Exception("Mismatching vectors");
84 }
85
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +010086 outputTensors.reserve(numOutputs);
87
Derek Lambertid6cb30e2020-04-28 13:31:29 +010088 for (size_t i = 0; i < numOutputs; i++)
89 {
90 const armnn::BindingPointInfo& outputBinding = outputBindings[i];
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +010091 const TContainer& outputData = outputDataContainers[i].get();
Derek Lambertid6cb30e2020-04-28 13:31:29 +010092
93 armnn::Tensor outputTensor(outputBinding.second, const_cast<float*>(outputData.data()));
94 outputTensors.push_back(std::make_pair(outputBinding.first, outputTensor));
95 }
96
97 return outputTensors;
98}
99
Derek Lambertifbab30b2020-09-17 13:58:18 +0100100#define S_BOOL(name) enum class name {False=0, True=1};
101
102S_BOOL(ImportMemory)
103S_BOOL(DumpToDot)
104S_BOOL(ExpectFile)
105S_BOOL(OptionalArg)
106
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100107int LoadModel(const char* filename,
108 ITfLiteParser& parser,
109 IRuntime& runtime,
110 NetworkId& networkId,
Narumol Prangnawaratef6f3002020-08-17 17:02:12 +0100111 const std::vector<BackendId>& backendPreferences,
Derek Lambertifbab30b2020-09-17 13:58:18 +0100112 ImportMemory enableImport,
113 DumpToDot dumpToDot)
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100114{
115 std::ifstream stream(filename, std::ios::in | std::ios::binary);
116 if (!stream.is_open())
117 {
118 ARMNN_LOG(error) << "Could not open model: " << filename;
119 return OPEN_FILE_ERROR;
120 }
121
122 std::vector<uint8_t> contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
123 stream.close();
124
125 auto model = parser.CreateNetworkFromBinary(contents);
126 contents.clear();
127 ARMNN_LOG(debug) << "Model loaded ok: " << filename;
128
129 // Optimize backbone model
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100130 OptimizerOptions options;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100131 options.m_ImportEnabled = enableImport != ImportMemory::False;
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100132 auto optimizedModel = Optimize(*model, backendPreferences, runtime.GetDeviceSpec(), options);
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100133 if (!optimizedModel)
134 {
135 ARMNN_LOG(fatal) << "Could not optimize the model:" << filename;
136 return OPTIMIZE_NETWORK_ERROR;
137 }
138
Derek Lambertifbab30b2020-09-17 13:58:18 +0100139 if (dumpToDot != DumpToDot::False)
140 {
141 std::stringstream ss;
142 ss << filename << ".dot";
143 std::ofstream dotStream(ss.str().c_str(), std::ofstream::out);
144 optimizedModel->SerializeToDot(dotStream);
145 dotStream.close();
146 }
Narumol Prangnawaratef6f3002020-08-17 17:02:12 +0100147 // Load model into runtime
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100148 {
149 std::string errorMessage;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100150 INetworkProperties modelProps(options.m_ImportEnabled, options.m_ImportEnabled);
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100151 Status status = runtime.LoadNetwork(networkId, std::move(optimizedModel), errorMessage, modelProps);
152 if (status != Status::Success)
153 {
154 ARMNN_LOG(fatal) << "Could not load " << filename << " model into runtime: " << errorMessage;
155 return LOAD_NETWORK_ERROR;
156 }
157 }
158
159 return 0;
160}
161
162std::vector<float> LoadImage(const char* filename)
163{
Derek Lambertifbab30b2020-09-17 13:58:18 +0100164 if (strlen(filename) == 0)
165 {
166 return std::vector<float>(1920*10180*3, 0.0f);
167 }
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100168 struct Memory
169 {
170 ~Memory() {stbi_image_free(m_Data);}
171 bool IsLoaded() const { return m_Data != nullptr;}
172
173 unsigned char* m_Data;
174 };
175
176 std::vector<float> image;
177
178 int width;
179 int height;
180 int channels;
181
182 Memory mem = {stbi_load(filename, &width, &height, &channels, 3)};
183 if (!mem.IsLoaded())
184 {
185 ARMNN_LOG(error) << "Could not load input image file: " << filename;
186 return image;
187 }
188
189 if (width != 1920 || height != 1080 || channels != 3)
190 {
191 ARMNN_LOG(error) << "Input image has wong dimension: " << width << "x" << height << "x" << channels << ". "
192 " Expected 1920x1080x3.";
193 return image;
194 }
195
196 image.resize(1920*1080*3);
197
198 // Expand to float. Does this need de-gamma?
199 for (unsigned int idx=0; idx <= 1920*1080*3; idx++)
200 {
201 image[idx] = static_cast<float>(mem.m_Data[idx]) /255.0f;
202 }
203
204 return image;
205}
206
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100207
Derek Lambertifbab30b2020-09-17 13:58:18 +0100208bool ValidateFilePath(std::string& file, ExpectFile expectFile)
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100209{
210 if (!ghc::filesystem::exists(file))
211 {
212 std::cerr << "Given file path " << file << " does not exist" << std::endl;
213 return false;
214 }
Derek Lambertifbab30b2020-09-17 13:58:18 +0100215 if (!ghc::filesystem::is_regular_file(file) && expectFile == ExpectFile::True)
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100216 {
217 std::cerr << "Given file path " << file << " is not a regular file" << std::endl;
218 return false;
219 }
220 return true;
221}
222
Ryan OShea74af0932020-08-07 16:27:34 +0100223void CheckAccuracy(std::vector<float>* toDetector0, std::vector<float>* toDetector1,
224 std::vector<float>* toDetector2, std::vector<float>* detectorOutput,
225 const std::vector<yolov3::Detection>& nmsOut, const std::vector<std::string>& filePaths)
226{
227 std::ifstream pathStream;
228 std::vector<float> expected;
229 std::vector<std::vector<float>*> outputs;
230 float compare = 0;
231 unsigned int count = 0;
232
233 //Push back output vectors from inference for use in loop
234 outputs.push_back(toDetector0);
235 outputs.push_back(toDetector1);
236 outputs.push_back(toDetector2);
237 outputs.push_back(detectorOutput);
238
239 for (unsigned int i = 0; i < outputs.size(); ++i)
240 {
241 // Reading expected output files and assigning them to @expected. Close and Clear to reuse stream and clean RAM
242 pathStream.open(filePaths[i]);
243 if (!pathStream.is_open())
244 {
245 ARMNN_LOG(error) << "Expected output file can not be opened: " << filePaths[i];
246 continue;
247 }
248
249 expected.assign(std::istream_iterator<float>(pathStream), {});
250 pathStream.close();
251 pathStream.clear();
252
253 // Ensure each vector is the same length
254 if (expected.size() != outputs[i]->size())
255 {
256 ARMNN_LOG(error) << "Expected output size does not match actual output size: " << filePaths[i];
257 }
258 else
259 {
260 count = 0;
261
262 // Compare abs(difference) with tolerance to check for value by value equality
263 for (unsigned int j = 0; j < outputs[i]->size(); ++j)
264 {
Keith Mok16fb1a22021-03-19 08:58:44 -0700265 compare = std::abs(expected[j] - outputs[i]->at(j));
Ryan OShea74af0932020-08-07 16:27:34 +0100266 if (compare > 0.001f)
267 {
268 count++;
269 }
270 }
271 if (count > 0)
272 {
273 ARMNN_LOG(error) << count << " output(s) do not match expected values in: " << filePaths[i];
274 }
275 }
276 }
277
278 pathStream.open(filePaths[4]);
279 if (!pathStream.is_open())
280 {
281 ARMNN_LOG(error) << "Expected output file can not be opened: " << filePaths[4];
282 }
283 else
284 {
285 expected.assign(std::istream_iterator<float>(pathStream), {});
286 pathStream.close();
287 pathStream.clear();
288 unsigned int y = 0;
289 unsigned int numOfMember = 6;
290 std::vector<float> intermediate;
291
292 for (auto& detection: nmsOut)
293 {
294 for (unsigned int x = y * numOfMember; x < ((y * numOfMember) + numOfMember); ++x)
295 {
296 intermediate.push_back(expected[x]);
297 }
298 if (!yolov3::compare_detection(detection, intermediate))
299 {
300 ARMNN_LOG(error) << "Expected NMS output does not match: Detection " << y + 1;
301 }
302 intermediate.clear();
303 y++;
304 }
305 }
306}
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100307
308struct ParseArgs
309{
310 ParseArgs(int ac, char *av[]) : options{"TfLiteYoloV3Big-Armnn",
311 "Executes YoloV3Big using ArmNN. YoloV3Big consists "
312 "of 3 parts: A backbone TfLite model, a detector TfLite "
313 "model, and None Maximum Suppression. All parts are "
314 "executed successively."}
315 {
316 options.add_options()
317 ("b,backbone-path",
318 "File path where the TfLite model for the yoloV3big backbone "
319 "can be found e.g. mydir/yoloV3big_backbone.tflite",
320 cxxopts::value<std::string>())
321
Ryan OShea74af0932020-08-07 16:27:34 +0100322 ("c,comparison-files",
323 "Defines the expected outputs for the model "
324 "of yoloV3big e.g. 'mydir/file1.txt,mydir/file2.txt,mydir/file3.txt,mydir/file4.txt'->InputToDetector1"
325 " will be tried first then InputToDetector2 then InputToDetector3 then the Detector Output and finally"
326 " the NMS output. NOTE: Files are passed as comma separated list without whitespaces.",
Derek Lambertifa4c1d12020-12-07 13:56:40 +0000327 cxxopts::value<std::vector<std::string>>()->default_value({}))
Ryan OShea74af0932020-08-07 16:27:34 +0100328
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100329 ("d,detector-path",
330 "File path where the TfLite model for the yoloV3big "
331 "detector can be found e.g.'mydir/yoloV3big_detector.tflite'",
332 cxxopts::value<std::string>())
333
334 ("h,help", "Produce help message")
335
336 ("i,image-path",
337 "File path to a 1080x1920 jpg image that should be "
338 "processed e.g. 'mydir/example_img_180_1920.jpg'",
339 cxxopts::value<std::string>())
340
341 ("B,preferred-backends-backbone",
342 "Defines the preferred backends to run the backbone model "
343 "of yoloV3big e.g. 'GpuAcc,CpuRef' -> GpuAcc will be tried "
344 "first before falling back to CpuRef. NOTE: Backends are passed "
345 "as comma separated list without whitespaces.",
346 cxxopts::value<std::vector<std::string>>()->default_value("GpuAcc,CpuRef"))
347
348 ("D,preferred-backends-detector",
349 "Defines the preferred backends to run the detector model "
350 "of yoloV3big e.g. 'CpuAcc,CpuRef' -> CpuAcc will be tried "
351 "first before falling back to CpuRef. NOTE: Backends are passed "
352 "as comma separated list without whitespaces.",
Derek Lambertifbab30b2020-09-17 13:58:18 +0100353 cxxopts::value<std::vector<std::string>>()->default_value("CpuAcc,CpuRef"))
354
355 ("M, model-to-dot",
356 "Dump the optimized model to a dot file for debugging/analysis",
357 cxxopts::value<bool>()->default_value("false"))
358
359 ("Y, dynamic-backends-path",
360 "Define a path from which to load any dynamic backends.",
361 cxxopts::value<std::string>());
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100362
363 auto result = options.parse(ac, av);
364
365 if (result.count("help"))
366 {
367 std::cout << options.help() << "\n";
368 exit(EXIT_SUCCESS);
369 }
370
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100371
Derek Lambertifbab30b2020-09-17 13:58:18 +0100372 backboneDir = GetPathArgument(result, "backbone-path", ExpectFile::True, OptionalArg::False);
Ryan OShea74af0932020-08-07 16:27:34 +0100373
Derek Lambertifbab30b2020-09-17 13:58:18 +0100374 comparisonFiles = GetPathArgument(result["comparison-files"].as<std::vector<std::string>>(), OptionalArg::True);
375
376 detectorDir = GetPathArgument(result, "detector-path", ExpectFile::True, OptionalArg::False);
377
378 imageDir = GetPathArgument(result, "image-path", ExpectFile::True, OptionalArg::True);
379
380 dynamicBackendPath = GetPathArgument(result, "dynamic-backends-path", ExpectFile::False, OptionalArg::True);
Ryan OShea74af0932020-08-07 16:27:34 +0100381
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100382 prefBackendsBackbone = GetBackendIDs(result["preferred-backends-backbone"].as<std::vector<std::string>>());
383 LogBackendsInfo(prefBackendsBackbone, "Backbone");
384 prefBackendsDetector = GetBackendIDs(result["preferred-backends-detector"].as<std::vector<std::string>>());
385 LogBackendsInfo(prefBackendsDetector, "detector");
Derek Lambertifbab30b2020-09-17 13:58:18 +0100386
387 dumpToDot = result["model-to-dot"].as<bool>() ? DumpToDot::True : DumpToDot::False;
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100388 }
389
390 /// Takes a vector of backend strings and returns a vector of backendIDs
391 std::vector<BackendId> GetBackendIDs(const std::vector<std::string>& backendStrings)
392 {
393 std::vector<BackendId> backendIDs;
394 for (const auto& b : backendStrings)
395 {
396 backendIDs.push_back(BackendId(b));
397 }
398 return backendIDs;
399 }
400
401 /// Verifies if the program argument with the name argName contains a valid file path.
402 /// Returns the valid file path string if given argument is associated a valid file path.
403 /// Otherwise throws an exception.
Derek Lambertifbab30b2020-09-17 13:58:18 +0100404 std::string GetPathArgument(cxxopts::ParseResult& result,
405 std::string&& argName,
406 ExpectFile expectFile,
407 OptionalArg isOptionalArg)
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100408 {
409 if (result.count(argName))
410 {
Derek Lambertifbab30b2020-09-17 13:58:18 +0100411 std::string path = result[argName].as<std::string>();
412 if (!ValidateFilePath(path, expectFile))
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100413 {
Derek Lambertifbab30b2020-09-17 13:58:18 +0100414 std::stringstream ss;
415 ss << "Argument given to" << argName << "is not a valid file path";
416 throw cxxopts::option_syntax_exception(ss.str().c_str());
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100417 }
Derek Lambertifbab30b2020-09-17 13:58:18 +0100418 return path;
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100419 }
420 else
421 {
Derek Lambertifbab30b2020-09-17 13:58:18 +0100422 if (isOptionalArg == OptionalArg::True)
423 {
424 return "";
425 }
426
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100427 throw cxxopts::missing_argument_exception(argName);
428 }
429 }
430
Ryan OShea74af0932020-08-07 16:27:34 +0100431 /// Assigns vector of strings to struct member variable
Derek Lambertifbab30b2020-09-17 13:58:18 +0100432 std::vector<std::string> GetPathArgument(const std::vector<std::string>& pathStrings, OptionalArg isOptional)
Ryan OShea74af0932020-08-07 16:27:34 +0100433 {
434 if (pathStrings.size() < 5){
Derek Lambertifbab30b2020-09-17 13:58:18 +0100435 if (isOptional == OptionalArg::True)
436 {
437 return std::vector<std::string>();
438 }
Ryan OShea74af0932020-08-07 16:27:34 +0100439 throw cxxopts::option_syntax_exception("Comparison files requires 5 file paths.");
440 }
441
442 std::vector<std::string> filePaths;
443 for (auto& path : pathStrings)
444 {
445 filePaths.push_back(path);
Derek Lambertifbab30b2020-09-17 13:58:18 +0100446 if (!ValidateFilePath(filePaths.back(), ExpectFile::True))
Ryan OShea74af0932020-08-07 16:27:34 +0100447 {
448 throw cxxopts::option_syntax_exception("Argument given to Comparison Files is not a valid file path");
449 }
450 }
451 return filePaths;
452 }
453
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100454 /// Log info about assigned backends
455 void LogBackendsInfo(std::vector<BackendId>& backends, std::string&& modelName)
456 {
457 std::string info;
458 info = "Preferred backends for " + modelName + " set to [ ";
459 for (auto const &backend : backends)
460 {
461 info = info + std::string(backend) + " ";
462 }
463 ARMNN_LOG(info) << info << "]";
464 }
465
466 // Member variables
467 std::string backboneDir;
Ryan OShea74af0932020-08-07 16:27:34 +0100468 std::vector<std::string> comparisonFiles;
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100469 std::string detectorDir;
470 std::string imageDir;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100471 std::string dynamicBackendPath;
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100472
473 std::vector<BackendId> prefBackendsBackbone;
474 std::vector<BackendId> prefBackendsDetector;
475
476 cxxopts::Options options;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100477
478 DumpToDot dumpToDot;
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100479};
480
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100481int main(int argc, char* argv[])
482{
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100483 // Configure logging
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100484 SetAllLoggingSinks(true, true, true);
485 SetLogFilter(LogSeverity::Trace);
486
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100487 // Check and get given program arguments
488 ParseArgs progArgs = ParseArgs(argc, argv);
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100489
490 // Create runtime
491 IRuntime::CreationOptions runtimeOptions; // default
Derek Lambertifbab30b2020-09-17 13:58:18 +0100492
493 if (!progArgs.dynamicBackendPath.empty())
494 {
495 std::cout << "Loading backends from" << progArgs.dynamicBackendPath << "\n";
496 runtimeOptions.m_DynamicBackendsPath = progArgs.dynamicBackendPath;
497 }
498
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100499 auto runtime = IRuntime::Create(runtimeOptions);
500 if (!runtime)
501 {
502 ARMNN_LOG(fatal) << "Could not create runtime.";
503 return -1;
504 }
505
506 // Create TfLite Parsers
507 ITfLiteParser::TfLiteParserOptions parserOptions;
508 auto parser = ITfLiteParser::Create(parserOptions);
509
510 // Load backbone model
511 ARMNN_LOG(info) << "Loading backbone...";
512 NetworkId backboneId;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100513 const DumpToDot dumpToDot = progArgs.dumpToDot;
514 CHECK_OK(LoadModel(progArgs.backboneDir.c_str(),
515 *parser,
516 *runtime,
517 backboneId,
518 progArgs.prefBackendsBackbone,
519 ImportMemory::False,
520 dumpToDot));
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100521 auto inputId = parser->GetNetworkInputBindingInfo(0, "inputs");
522 auto bbOut0Id = parser->GetNetworkOutputBindingInfo(0, "input_to_detector_1");
523 auto bbOut1Id = parser->GetNetworkOutputBindingInfo(0, "input_to_detector_2");
524 auto bbOut2Id = parser->GetNetworkOutputBindingInfo(0, "input_to_detector_3");
525 auto backboneProfile = runtime->GetProfiler(backboneId);
526 backboneProfile->EnableProfiling(true);
527
Derek Lambertifbab30b2020-09-17 13:58:18 +0100528
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100529 // Load detector model
530 ARMNN_LOG(info) << "Loading detector...";
531 NetworkId detectorId;
Derek Lambertifbab30b2020-09-17 13:58:18 +0100532 CHECK_OK(LoadModel(progArgs.detectorDir.c_str(),
533 *parser,
534 *runtime,
535 detectorId,
536 progArgs.prefBackendsDetector,
537 ImportMemory::True,
538 dumpToDot));
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100539 auto detectIn0Id = parser->GetNetworkInputBindingInfo(0, "input_to_detector_1");
540 auto detectIn1Id = parser->GetNetworkInputBindingInfo(0, "input_to_detector_2");
541 auto detectIn2Id = parser->GetNetworkInputBindingInfo(0, "input_to_detector_3");
542 auto outputBoxesId = parser->GetNetworkOutputBindingInfo(0, "output_boxes");
543 auto detectorProfile = runtime->GetProfiler(detectorId);
544
545 // Load input from file
546 ARMNN_LOG(info) << "Loading test image...";
Jan Eilerse7cc7c32020-06-25 13:18:47 +0100547 auto image = LoadImage(progArgs.imageDir.c_str());
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100548 if (image.empty())
549 {
550 return LOAD_IMAGE_ERROR;
551 }
552
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100553 // Allocate the intermediate tensors
554 std::vector<float> intermediateMem0(bbOut0Id.second.GetNumElements());
555 std::vector<float> intermediateMem1(bbOut1Id.second.GetNumElements());
556 std::vector<float> intermediateMem2(bbOut2Id.second.GetNumElements());
557 std::vector<float> intermediateMem3(outputBoxesId.second.GetNumElements());
558
559 // Setup inputs and outputs
560 using BindingInfos = std::vector<armnn::BindingPointInfo>;
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +0100561 using FloatTensors = std::vector<std::reference_wrapper<std::vector<float>>>;
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100562
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +0100563 InputTensors bbInputTensors = MakeInputTensors(BindingInfos{ inputId },
564 FloatTensors{ image });
565 OutputTensors bbOutputTensors = MakeOutputTensors(BindingInfos{ bbOut0Id, bbOut1Id, bbOut2Id },
566 FloatTensors{ intermediateMem0,
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100567 intermediateMem1,
Narumol Prangnawarat2adf5f02020-07-21 10:21:19 +0100568 intermediateMem2 });
569 InputTensors detectInputTensors = MakeInputTensors(BindingInfos{ detectIn0Id,
570 detectIn1Id,
571 detectIn2Id } ,
572 FloatTensors{ intermediateMem0,
573 intermediateMem1,
574 intermediateMem2 });
575 OutputTensors detectOutputTensors = MakeOutputTensors(BindingInfos{ outputBoxesId },
576 FloatTensors{ intermediateMem3 });
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100577
578 static const int numIterations=2;
579 using DurationUS = std::chrono::duration<double, std::micro>;
580 std::vector<DurationUS> nmsDurations(0);
Ryan OShea74af0932020-08-07 16:27:34 +0100581 std::vector<yolov3::Detection> filtered_boxes;
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100582 nmsDurations.reserve(numIterations);
583 for (int i=0; i < numIterations; i++)
584 {
585 // Execute backbone
586 ARMNN_LOG(info) << "Running backbone...";
587 runtime->EnqueueWorkload(backboneId, bbInputTensors, bbOutputTensors);
588
589 // Execute detector
590 ARMNN_LOG(info) << "Running detector...";
591 runtime->EnqueueWorkload(detectorId, detectInputTensors, detectOutputTensors);
592
593 // Execute NMS
594 ARMNN_LOG(info) << "Running nms...";
595 using clock = std::chrono::steady_clock;
596 auto nmsStartTime = clock::now();
597 yolov3::NMSConfig config;
598 config.num_boxes = 127800;
599 config.num_classes = 80;
600 config.confidence_threshold = 0.9f;
601 config.iou_threshold = 0.5f;
Ryan OShea74af0932020-08-07 16:27:34 +0100602 filtered_boxes = yolov3::nms(config, intermediateMem3);
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100603 auto nmsEndTime = clock::now();
604
605 // Enable the profiling after the warm-up run
606 if (i>0)
607 {
608 print_detection(std::cout, filtered_boxes);
609
610 const auto nmsDuration = DurationUS(nmsStartTime - nmsEndTime);
611 nmsDurations.push_back(nmsDuration);
612 }
613 backboneProfile->EnableProfiling(true);
614 detectorProfile->EnableProfiling(true);
615 }
616 // Log timings to file
617 std::ofstream backboneProfileStream("backbone.json");
618 backboneProfile->Print(backboneProfileStream);
619 backboneProfileStream.close();
620
621 std::ofstream detectorProfileStream("detector.json");
622 detectorProfile->Print(detectorProfileStream);
623 detectorProfileStream.close();
624
625 // Manually construct the json output
626 std::ofstream nmsProfileStream("nms.json");
627 nmsProfileStream << "{" << "\n";
628 nmsProfileStream << R"( "NmsTimings": {)" << "\n";
629 nmsProfileStream << R"( "raw": [)" << "\n";
630 bool isFirst = true;
631 for (auto duration : nmsDurations)
632 {
633 if (!isFirst)
634 {
635 nmsProfileStream << ",\n";
636 }
637
638 nmsProfileStream << " " << duration.count();
639 isFirst = false;
640 }
641 nmsProfileStream << "\n";
642 nmsProfileStream << R"( "units": "us")" << "\n";
643 nmsProfileStream << " ]" << "\n";
644 nmsProfileStream << " }" << "\n";
645 nmsProfileStream << "}" << "\n";
646 nmsProfileStream.close();
647
Derek Lambertifbab30b2020-09-17 13:58:18 +0100648 if (progArgs.comparisonFiles.size() > 0)
649 {
650 CheckAccuracy(&intermediateMem0,
651 &intermediateMem1,
652 &intermediateMem2,
653 &intermediateMem3,
654 filtered_boxes,
655 progArgs.comparisonFiles);
656 }
Ryan OShea74af0932020-08-07 16:27:34 +0100657
Derek Lambertid6cb30e2020-04-28 13:31:29 +0100658 ARMNN_LOG(info) << "Run completed";
659 return 0;
Keith Mok16fb1a22021-03-19 08:58:44 -0700660}