test_ie_models.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. //
  5. // Copyright (C) 2018-2019, Intel Corporation, all rights reserved.
  6. // Third party copyrights are property of their respective owners.
  7. #include "test_precomp.hpp"
  8. #ifdef HAVE_INF_ENGINE
  9. #include <opencv2/core/utils/filesystem.hpp>
  10. //
  11. // Synchronize headers include statements with src/op_inf_engine.hpp
  12. //
  13. //#define INFERENCE_ENGINE_DEPRECATED // turn off deprecation warnings from IE
  14. //there is no way to suppress warnings from IE only at this moment, so we are forced to suppress warnings globally
  15. #if defined(__GNUC__)
  16. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  17. #endif
  18. #ifdef _MSC_VER
  19. #pragma warning(disable: 4996) // was declared deprecated
  20. #endif
  21. #if defined(__GNUC__)
  22. #pragma GCC visibility push(default)
  23. #endif
  24. #if defined(__GNUC__)
  25. #pragma GCC visibility pop
  26. #endif
  27. #include <openvino/runtime/core.hpp>
  28. namespace opencv_test { namespace {
  29. static void initDLDTDataPath()
  30. {
  31. #ifndef WINRT
  32. static bool initialized = false;
  33. if (!initialized)
  34. {
  35. #if INF_ENGINE_RELEASE <= 2018050000
  36. cvtest::addDataSearchEnv("INTEL_CVSDK_DIR");
  37. #else
  38. cvtest::addDataSearchEnv("OPENCV_OPEN_MODEL_ZOO_DATA_PATH");
  39. const std::string dnnDataPath = cv::utils::getConfigurationParameterString("OPENCV_DNN_TEST_DATA_PATH");
  40. if (!dnnDataPath.empty())
  41. cvtest::addDataSearchPath(std::string(dnnDataPath) + "/omz_intel_models");
  42. #endif
  43. initialized = true;
  44. }
  45. #endif
  46. }
  47. using namespace cv;
  48. using namespace cv::dnn;
  49. struct OpenVINOModelTestCaseInfo
  50. {
  51. const char* modelPathFP32;
  52. const char* modelPathFP16;
  53. };
  54. static const std::map<std::string, OpenVINOModelTestCaseInfo>& getOpenVINOTestModels()
  55. {
  56. static std::map<std::string, OpenVINOModelTestCaseInfo> g_models {
  57. #if INF_ENGINE_RELEASE >= 2018050000 && \
  58. INF_ENGINE_RELEASE <= 2020999999 // don't use IRv5 models with 2020.1+
  59. // layout is defined by open_model_zoo/model_downloader
  60. // Downloaded using these parameters for Open Model Zoo downloader (2019R1):
  61. // ./downloader.py -o ${OPENCV_DNN_TEST_DATA_PATH}/omz_intel_models --cache_dir ${OPENCV_DNN_TEST_DATA_PATH}/.omz_cache/ \
  62. // --name face-person-detection-retail-0002,face-person-detection-retail-0002-fp16,age-gender-recognition-retail-0013,age-gender-recognition-retail-0013-fp16,head-pose-estimation-adas-0001,head-pose-estimation-adas-0001-fp16,person-detection-retail-0002,person-detection-retail-0002-fp16,vehicle-detection-adas-0002,vehicle-detection-adas-0002-fp16
  63. { "age-gender-recognition-retail-0013", {
  64. "Retail/object_attributes/age_gender/dldt/age-gender-recognition-retail-0013",
  65. "Retail/object_attributes/age_gender/dldt/age-gender-recognition-retail-0013-fp16"
  66. }},
  67. { "face-person-detection-retail-0002", {
  68. "Retail/object_detection/face_pedestrian/rmnet-ssssd-2heads/0002/dldt/face-person-detection-retail-0002",
  69. "Retail/object_detection/face_pedestrian/rmnet-ssssd-2heads/0002/dldt/face-person-detection-retail-0002-fp16"
  70. }},
  71. { "head-pose-estimation-adas-0001", {
  72. "Transportation/object_attributes/headpose/vanilla_cnn/dldt/head-pose-estimation-adas-0001",
  73. "Transportation/object_attributes/headpose/vanilla_cnn/dldt/head-pose-estimation-adas-0001-fp16"
  74. }},
  75. { "person-detection-retail-0002", {
  76. "Retail/object_detection/pedestrian/hypernet-rfcn/0026/dldt/person-detection-retail-0002",
  77. "Retail/object_detection/pedestrian/hypernet-rfcn/0026/dldt/person-detection-retail-0002-fp16"
  78. }},
  79. { "vehicle-detection-adas-0002", {
  80. "Transportation/object_detection/vehicle/mobilenet-reduced-ssd/dldt/vehicle-detection-adas-0002",
  81. "Transportation/object_detection/vehicle/mobilenet-reduced-ssd/dldt/vehicle-detection-adas-0002-fp16"
  82. }},
  83. #endif
  84. #if INF_ENGINE_RELEASE >= 2020010000
  85. // Downloaded using these parameters for Open Model Zoo downloader (2020.1):
  86. // ./downloader.py -o ${OPENCV_DNN_TEST_DATA_PATH}/omz_intel_models --cache_dir ${OPENCV_DNN_TEST_DATA_PATH}/.omz_cache/ \
  87. // --name person-detection-retail-0013,age-gender-recognition-retail-0013
  88. { "person-detection-retail-0013", { // IRv10
  89. "intel/person-detection-retail-0013/FP32/person-detection-retail-0013",
  90. "intel/person-detection-retail-0013/FP16/person-detection-retail-0013"
  91. }},
  92. { "age-gender-recognition-retail-0013", {
  93. "intel/age-gender-recognition-retail-0013/FP16/age-gender-recognition-retail-0013",
  94. "intel/age-gender-recognition-retail-0013/FP32/age-gender-recognition-retail-0013"
  95. }},
  96. #endif
  97. };
  98. return g_models;
  99. }
  100. static const std::vector<std::string> getOpenVINOTestModelsList()
  101. {
  102. std::vector<std::string> result;
  103. const std::map<std::string, OpenVINOModelTestCaseInfo>& models = getOpenVINOTestModels();
  104. for (const auto& it : models)
  105. result.push_back(it.first);
  106. return result;
  107. }
  108. inline static std::string getOpenVINOModel(const std::string &modelName, bool isFP16)
  109. {
  110. const std::map<std::string, OpenVINOModelTestCaseInfo>& models = getOpenVINOTestModels();
  111. const auto it = models.find(modelName);
  112. if (it != models.end())
  113. {
  114. OpenVINOModelTestCaseInfo modelInfo = it->second;
  115. if (isFP16 && modelInfo.modelPathFP16)
  116. return std::string(modelInfo.modelPathFP16);
  117. else if (!isFP16 && modelInfo.modelPathFP32)
  118. return std::string(modelInfo.modelPathFP32);
  119. }
  120. return std::string();
  121. }
  122. void runIE(Target target, const std::string& xmlPath, const std::string& binPath,
  123. std::map<std::string, cv::Mat>& inputsMap, std::map<std::string, cv::Mat>& outputsMap)
  124. {
  125. SCOPED_TRACE("runIE");
  126. std::string device_name;
  127. ov::Core core;
  128. auto model = core.read_model(xmlPath, binPath);
  129. ov::CompiledModel compiledModel;
  130. ov::InferRequest infRequest;
  131. try
  132. {
  133. switch (target)
  134. {
  135. case DNN_TARGET_CPU:
  136. device_name = "CPU";
  137. break;
  138. case DNN_TARGET_OPENCL:
  139. case DNN_TARGET_OPENCL_FP16:
  140. device_name = "GPU";
  141. break;
  142. case DNN_TARGET_MYRIAD:
  143. device_name = "MYRIAD";
  144. break;
  145. case DNN_TARGET_FPGA:
  146. device_name = "FPGA";
  147. break;
  148. default:
  149. CV_Error(Error::StsNotImplemented, "Unknown target");
  150. };
  151. if (target == DNN_TARGET_CPU || target == DNN_TARGET_FPGA)
  152. {
  153. std::string suffixes[] = {"_avx2", "_sse4", ""};
  154. bool haveFeature[] = {
  155. checkHardwareSupport(CPU_AVX2),
  156. checkHardwareSupport(CPU_SSE4_2),
  157. true
  158. };
  159. for (int i = 0; i < 3; ++i)
  160. {
  161. if (!haveFeature[i])
  162. continue;
  163. #ifdef _WIN32
  164. std::string libName = "cpu_extension" + suffixes[i] + ".dll";
  165. #elif defined(__APPLE__)
  166. std::string libName = "libcpu_extension" + suffixes[i] + ".dylib";
  167. #else
  168. std::string libName = "libcpu_extension" + suffixes[i] + ".so";
  169. #endif // _WIN32
  170. try
  171. {
  172. core.add_extension(libName);
  173. break;
  174. }
  175. catch(...) {}
  176. }
  177. // Some of networks can work without a library of extra layers.
  178. }
  179. compiledModel = core.compile_model(model, device_name);
  180. infRequest = compiledModel.create_infer_request();
  181. }
  182. catch (const std::exception& ex)
  183. {
  184. CV_Error(Error::StsAssert, format("Failed to initialize Inference Engine backend: %s", ex.what()));
  185. }
  186. // Fill input tensors.
  187. inputsMap.clear();
  188. for (auto&& it : model->inputs())
  189. {
  190. auto type = it.get_element_type();
  191. auto shape_ = it.get_partial_shape();
  192. if (shape_.is_dynamic())
  193. {
  194. FAIL() << "Model should not have dynamic shapes (" << it.get_any_name() << " => " << shape_ << ")";
  195. }
  196. auto shape = shape_.to_shape();
  197. auto& m = inputsMap[it.get_any_name()];
  198. auto tensor = ov::Tensor(type, shape);
  199. if (type == ov::element::f32)
  200. {
  201. m.create(std::vector<int>(shape.begin(), shape.end()), CV_32F);
  202. randu(m, -1, 1);
  203. }
  204. else if (type == ov::element::i32)
  205. {
  206. m.create(std::vector<int>(shape.begin(), shape.end()), CV_32S);
  207. randu(m, -100, 100);
  208. }
  209. else
  210. {
  211. FAIL() << "Unsupported precision: " << type;
  212. }
  213. std::memcpy(tensor.data(), m.data, tensor.get_byte_size());
  214. if (cvtest::debugLevel > 0)
  215. {
  216. std::cout << "Input: '" << it.get_any_name() << "' precision=" << type << " dims=" << shape << " [";
  217. for (auto d : shape)
  218. std::cout << " " << d;
  219. std::cout << "] ocv_mat=" << inputsMap[it.get_any_name()].size << " of " << typeToString(inputsMap[it.get_any_name()].type()) << std::endl;
  220. }
  221. infRequest.set_tensor(it, tensor);
  222. }
  223. infRequest.infer();
  224. // Fill output tensors.
  225. outputsMap.clear();
  226. for (const auto& it : model->outputs())
  227. {
  228. auto type = it.get_element_type();
  229. auto& m = outputsMap[it.get_any_name()];
  230. auto tensor = infRequest.get_tensor(it);
  231. auto shape = tensor.get_shape();
  232. if (type == ov::element::f32)
  233. {
  234. m.create(std::vector<int>(shape.begin(), shape.end()), CV_32F);
  235. }
  236. else if (type == ov::element::i32)
  237. {
  238. m.create(std::vector<int>(shape.begin(), shape.end()), CV_32S);
  239. }
  240. else
  241. {
  242. FAIL() << "Unsupported precision: " << type;
  243. }
  244. std::memcpy(m.data, tensor.data(), tensor.get_byte_size());
  245. if (cvtest::debugLevel > 0)
  246. {
  247. std::cout << "Output: '" << it.get_any_name() << "' precision=" << type << " dims=" << shape << " [";
  248. for (auto d : shape)
  249. std::cout << " " << d;
  250. std::cout << "] ocv_mat=" << outputsMap[it.get_any_name()].size << " of " << typeToString(outputsMap[it.get_any_name()].type()) << std::endl;
  251. }
  252. }
  253. }
  254. void runCV(Backend backendId, Target targetId, const std::string& xmlPath, const std::string& binPath,
  255. const std::map<std::string, cv::Mat>& inputsMap,
  256. std::map<std::string, cv::Mat>& outputsMap)
  257. {
  258. SCOPED_TRACE("runOCV");
  259. Net net = readNet(xmlPath, binPath);
  260. for (auto& it : inputsMap)
  261. net.setInput(it.second, it.first);
  262. net.setPreferableBackend(backendId);
  263. net.setPreferableTarget(targetId);
  264. std::vector<String> outNames = net.getUnconnectedOutLayersNames();
  265. if (cvtest::debugLevel > 0)
  266. {
  267. std::cout << "OpenCV output names: " << outNames.size() << std::endl;
  268. for (auto name : outNames)
  269. std::cout << "- " << name << std::endl;
  270. }
  271. std::vector<Mat> outs;
  272. net.forward(outs, outNames);
  273. outputsMap.clear();
  274. EXPECT_EQ(outs.size(), outNames.size());
  275. for (int i = 0; i < outs.size(); ++i)
  276. {
  277. EXPECT_TRUE(outputsMap.insert({outNames[i], outs[i]}).second);
  278. }
  279. }
  280. typedef TestWithParam<tuple< tuple<Backend, Target>, std::string> > DNNTestOpenVINO;
  281. TEST_P(DNNTestOpenVINO, models)
  282. {
  283. initDLDTDataPath();
  284. const Backend backendId = get<0>(get<0>(GetParam()));
  285. const Target targetId = get<1>(get<0>(GetParam()));
  286. std::string modelName = get<1>(GetParam());
  287. ASSERT_FALSE(backendId != DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && backendId != DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) <<
  288. "Inference Engine backend is required";
  289. #if INF_ENGINE_VER_MAJOR_GE(2021030000)
  290. if (targetId == DNN_TARGET_MYRIAD && (false
  291. || modelName == "person-detection-retail-0013" // ncDeviceOpen:1013 Failed to find booted device after boot
  292. || modelName == "age-gender-recognition-retail-0013" // ncDeviceOpen:1013 Failed to find booted device after boot
  293. )
  294. )
  295. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  296. #endif
  297. #if INF_ENGINE_VER_MAJOR_GE(2020020000)
  298. if (targetId == DNN_TARGET_MYRIAD && backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
  299. {
  300. if (modelName == "person-detection-retail-0013") // IRv10
  301. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NN_BUILDER, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  302. }
  303. #endif
  304. #if INF_ENGINE_VER_MAJOR_EQ(2020040000)
  305. if (targetId == DNN_TARGET_MYRIAD && modelName == "person-detection-retail-0002") // IRv5, OpenVINO 2020.4 regression
  306. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  307. #endif
  308. ASSERT_EQ(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, backendId);
  309. bool isFP16 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD);
  310. const std::string modelPath = getOpenVINOModel(modelName, isFP16);
  311. ASSERT_FALSE(modelPath.empty()) << modelName;
  312. std::string xmlPath = findDataFile(modelPath + ".xml", false);
  313. std::string binPath = findDataFile(modelPath + ".bin", false);
  314. std::map<std::string, cv::Mat> inputsMap;
  315. std::map<std::string, cv::Mat> ieOutputsMap, cvOutputsMap;
  316. // Single Myriad device cannot be shared across multiple processes.
  317. if (targetId == DNN_TARGET_MYRIAD)
  318. resetMyriadDevice();
  319. if (targetId == DNN_TARGET_HDDL)
  320. releaseHDDLPlugin();
  321. EXPECT_NO_THROW(runIE(targetId, xmlPath, binPath, inputsMap, ieOutputsMap)) << "runIE";
  322. if (targetId == DNN_TARGET_MYRIAD)
  323. resetMyriadDevice();
  324. EXPECT_NO_THROW(runCV(backendId, targetId, xmlPath, binPath, inputsMap, cvOutputsMap)) << "runCV";
  325. double eps = 0;
  326. #if INF_ENGINE_VER_MAJOR_GE(2020010000)
  327. if (targetId == DNN_TARGET_CPU && checkHardwareSupport(CV_CPU_AVX_512F))
  328. eps = 1e-5;
  329. #endif
  330. EXPECT_EQ(ieOutputsMap.size(), cvOutputsMap.size());
  331. for (auto& srcIt : ieOutputsMap)
  332. {
  333. auto dstIt = cvOutputsMap.find(srcIt.first);
  334. CV_Assert(dstIt != cvOutputsMap.end());
  335. dstIt->second.convertTo(dstIt->second, srcIt.second.type());
  336. double normInf = cvtest::norm(srcIt.second, dstIt->second, cv::NORM_INF);
  337. EXPECT_LE(normInf, eps) << "output=" << srcIt.first;
  338. }
  339. }
  340. INSTANTIATE_TEST_CASE_P(/**/,
  341. DNNTestOpenVINO,
  342. Combine(dnnBackendsAndTargetsIE(),
  343. testing::ValuesIn(getOpenVINOTestModelsList())
  344. )
  345. );
  346. typedef TestWithParam<Target> DNNTestHighLevelAPI;
  347. TEST_P(DNNTestHighLevelAPI, predict)
  348. {
  349. initDLDTDataPath();
  350. Target target = (dnn::Target)(int)GetParam();
  351. bool isFP16 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD);
  352. const std::string modelName = "age-gender-recognition-retail-0013";
  353. const std::string modelPath = getOpenVINOModel(modelName, isFP16);
  354. ASSERT_FALSE(modelPath.empty()) << modelName;
  355. std::string xmlPath = findDataFile(modelPath + ".xml", false);
  356. std::string binPath = findDataFile(modelPath + ".bin", false);
  357. Model model(xmlPath, binPath);
  358. Mat frame = imread(findDataFile("dnn/googlenet_1.png"));
  359. std::vector<Mat> outs;
  360. model.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
  361. model.setPreferableTarget(target);
  362. model.predict(frame, outs);
  363. Net net = readNet(xmlPath, binPath);
  364. Mat input = blobFromImage(frame, 1.0, Size(62, 62));
  365. net.setInput(input);
  366. net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
  367. net.setPreferableTarget(target);
  368. std::vector<String> outNames = net.getUnconnectedOutLayersNames();
  369. std::vector<Mat> refs;
  370. net.forward(refs, outNames);
  371. CV_Assert(refs.size() == outs.size());
  372. for (int i = 0; i < refs.size(); ++i)
  373. normAssert(outs[i], refs[i]);
  374. }
  375. INSTANTIATE_TEST_CASE_P(/**/,
  376. DNNTestHighLevelAPI, testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE))
  377. );
  378. }}
  379. #endif // HAVE_INF_ENGINE