OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "image_quality_helper.hpp"
#include "map_metric_helpers.hpp"
#include "openvino/core/partial_shape.hpp"
#include "semantic_segmentation_helpers.hpp"
#include "tensor_utils.hpp"
#include "yolo_helpers.hpp"
#include "tools_helpers.hpp"
#include "argument_parse_helpers.hpp"
#include <openvino/core/parallel.hpp>
#include <openvino/openvino.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <optional>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
using TensorMap = std::map<std::string, ov::Tensor>;
// Clamp +/-inf elements to the representable range of the buffer element type.
template <typename T>
static void clampInfInBuffer(T* data, size_t count) {
const T posMax = std::numeric_limits<T>::max();
const T negMin = std::numeric_limits<T>::lowest();
for (size_t i = 0; i < count; ++i) {
const float val = static_cast<float>(data[i]);
if (std::isinf(val)) {
data[i] = (val > 0.0f) ? posMax : negMin;
}
}
}
// Clamp +/-inf elements in a tensor in-place.
// Returns true on success; returns false for unsupported (non-float) element types.
static bool clampInfInTensor(ov::Tensor& tensor) {
const auto et = tensor.get_element_type();
const size_t count = tensor.get_size();
if (et == ov::element::f32) {
clampInfInBuffer(tensor.data<float>(), count);
return true;
} else if (et == ov::element::f16) {
clampInfInBuffer(tensor.data<ov::float16>(), count);
return true;
} else if (et == ov::element::bf16) {
clampInfInBuffer(tensor.data<ov::bfloat16>(), count);
return true;
}
return false;
}
struct TensorDescriptor {
ov::element::Type precision;
ov::PartialShape shape;
ov::Shape dataShape;
ov::Layout layout;
};
using TensorDescriptorMap = std::unordered_map<std::string, TensorDescriptor>;
typedef std::chrono::high_resolution_clock Time;
std::vector<std::string> splitStringList(const std::string& str, char delim) {
std::vector<std::string> out;
if (str.empty()) {
return out;
}
std::istringstream istr(str);
std::string elem;
while (std::getline(istr, elem, delim)) {
if (elem.empty()) {
continue;
}
out.push_back(std::move(elem));
}
return out;
}
std::vector<float> splitFloat(const std::string& s, char delim) {
std::vector<float> result;
std::stringstream ss(s);
std::string item;
while (getline(ss, item, delim)) {
result.push_back(std::stof(item));
}
return result;
}
std::string to_string(const std::vector<std::string>& c) {
std::stringstream stream;
std::string ret;
if (!c.empty()) {
stream << "[";
for (const auto &elem : c) {
stream << elem << ",";
}
ret = stream.str();
ret.pop_back();
ret += "]";
}
return ret;
}
std::map<std::string, std::string> parseArgMap(std::string argMap, char delimiter = ';') {
argMap.erase(std::remove_if(argMap.begin(), argMap.end(), ::isspace), argMap.end());
const auto pairs = splitStringList(argMap, delimiter);
std::map<std::string, std::string> parsedMap;
for (auto&& pair : pairs) {
const auto lastDelimPos = pair.find_last_of(':');
auto key = pair.substr(0, lastDelimPos);
std::string value;
if (lastDelimPos != std::string::npos) {
value = pair.substr(lastDelimPos + 1);
}
parsedMap[std::move(key)] = std::move(value);
}
return parsedMap;
}
//
// OpenCV to OpenVINO conversion
//
bool isImage(const ov::Shape& shape, const ov::Layout& layout) {
if (shape.size() == 4) {
const auto numChannels = shape[ov::layout::channels_idx(layout)];
return (numChannels == 3) || (numChannels == 4);
}
return false;
}
/**
* @brief Computes the offsets for each axis in terms of number of elements.
* @details Taken from the OpenVINO implementation ("InferenceEngine::BlockingDesc::fillDesc") and slightly modified for
* the current usecase.
*
* @param shape The shape based on which the offsets will be computed.
* @return The resulting strides.
*/
std::vector<size_t> getStrides(const ov::Shape& shape) {
std::vector<size_t> strides(shape.size());
strides[strides.size() - 1] = 1;
for (size_t i = 2; i <= shape.size(); i++) {
strides[strides.size() - i] = strides[strides.size() - (i - 1)] * shape[shape.size() - (i - 1)];
}
return strides;
}
std::vector<cv::Mat> ovToCV(ov::Tensor& tensor,
const ov::Shape& shape,
const ov::Layout& layout,
size_t batchInd = 0,
size_t depthInd = 0) {
const ov::element::Type& precision = tensor.get_element_type();
OPENVINO_ASSERT(layout == ov::Layout("NCHW") || layout == ov::Layout("NCDHW"),
"Unsupported layout: ", layout.to_string());
OPENVINO_ASSERT(precision == ov::element::Type_t::u8 || precision == ov::element::Type_t::f32 ||
precision == ov::element::Type_t::f16 || precision == ov::element::Type_t::bf16 ||
precision == ov::element::Type_t::i32,
"Unsupported precision: ", precision.get_type_name());
int cvType = 0;
size_t elemSize = 0;
if (precision == ov::element::Type_t::u8) {
cvType = CV_8UC1;
elemSize = sizeof(uint8_t);
} else if (precision == ov::element::Type_t::f32) {
cvType = CV_32FC1;
elemSize = sizeof(float);
} else if (precision == ov::element::Type_t::f16) {
cvType = CV_16SC1;
elemSize = sizeof(ov::float16);
} else if (precision == ov::element::Type_t::bf16) {
cvType = CV_16SC1;
elemSize = sizeof(ov::bfloat16);
} else if (precision == ov::element::Type_t::i32) {
cvType = CV_32SC1;
elemSize = sizeof(int32_t);
}
std::vector<cv::Mat> out;
const size_t N = shape[ov::layout::batch_idx(layout)];
const size_t C = shape[ov::layout::channels_idx(layout)];
const size_t H = shape[ov::layout::height_idx(layout)];
const size_t W = shape[ov::layout::width_idx(layout)];
const auto dataBuffer = reinterpret_cast<uint8_t*>(tensor.data());
if (layout == ov::Layout("NCHW")) {
OPENVINO_ASSERT(batchInd < N);
OPENVINO_ASSERT(C == 3 || C == 4, "Unsupported number of channels: ", C);
out.resize(C);
for (size_t c = 0; c < C; ++c) {
out[c] = cv::Mat(static_cast<int>(H), static_cast<int>(W), cvType,
dataBuffer + (batchInd * C + c) * W * H * elemSize);
}
} else if (layout == ov::Layout("NCDHW")) {
const size_t D = shape[ov::layout::depth_idx(layout)];
const std::vector<size_t> strides = getStrides(shape);
const auto strideN = strides[ov::layout::batch_idx(layout)];
const auto strideC = strides[ov::layout::channels_idx(layout)];
const auto strideD = strides[ov::layout::depth_idx(layout)];
OPENVINO_ASSERT(batchInd < N);
OPENVINO_ASSERT(depthInd < D);
OPENVINO_ASSERT(C == 3 || C == 4, "Unsupported number of channels: ", C);
out.resize(C);
for (size_t c = 0; c < C; ++c) {
out[c] = cv::Mat(static_cast<int>(H), static_cast<int>(W), cvType,
dataBuffer + (strideN * batchInd + strideC * c + strideD * depthInd) * elemSize);
}
}
return out;
}
/**
* @brief Converts the source data from its current precision to the one used by the destination buffer and then places
* the result inside it.
* @details The conversion is performed by the use of the "static_cast" operator. Depending on the types between which
* the conversions are made, this may lead to undefined behavior.
*
* E.g.: Several experiments suggest float<->ov::float16 conversions may work fine, but float->uint8_t may lead to
* division by zero.
*
* @tparam InT The type of the source buffer
* @tparam OutT The type of the destination buffer
* @param destination Where the result will be stored
* @param source The data which shall be converted
* @param numberOfElements Indicates how many elements will be taken from the source buffer.
*/
template <typename InT, typename OutT>
void convertBufferType(OutT* destination, const InT* source, size_t numberOfElements) {
ov::parallel_for(numberOfElements, [source, destination](int64_t index) {
destination[index] = static_cast<OutT>(source[index]);
});
}
struct BatchIndexer {
const size_t index = 0;
const size_t size = 1;
BatchIndexer(size_t lineIndex = 0, size_t lineCount = 1) : index(lineIndex), size(lineCount) {
OPENVINO_ASSERT(index < size, "Inconsistent parameters used for "
"BatchIndexer construction, lineIndex: ", index,
" must be lesser than lineCount: ", size);
}
std::string to_string() const {
std::stringstream sstream;
sstream << "[" << index << "/" << size << "]";
return sstream.str();
}
};
void cvToOV(const cv::Mat& cvImg,
const BatchIndexer& cvImgInBatch,
ov::Tensor& tensor,
const ov::Shape& shape,
const ov::Layout& layout,
const std::string& colorFormat) {
const ov::element::Type& precision = tensor.get_element_type();
OPENVINO_ASSERT(layout == ov::Layout("NHWC") || layout == ov::Layout("NCHW"),
"Unsupported layout: ", layout.to_string());
const auto N = shape[ov::layout::batch_idx(layout)];
const auto C = shape[ov::layout::channels_idx(layout)];
const auto H = shape[ov::layout::height_idx(layout)];
const auto W = shape[ov::layout::width_idx(layout)];
OPENVINO_ASSERT(C == 3 || C == 4, "Unsupported number of channels: ", C);
int cvType = 0;
if (precision == ov::element::Type_t::u8) {
cvType = static_cast<int>(CV_8UC(C));
} else if (precision == ov::element::Type_t::f32) {
cvType = static_cast<int>(CV_32FC(C));
} else if (precision == ov::element::Type_t::f16) {
cvType = static_cast<int>(CV_16SC(C));
} else if (precision == ov::element::Type_t::bf16) {
cvType = static_cast<int>(CV_16SC(C));
} else if (precision == ov::element::Type_t::i32) {
cvType = static_cast<int>(CV_32SC(C));
} else {
OPENVINO_ASSERT(precision == ov::element::Type_t::u8 || precision == ov::element::Type_t::f32 ||
precision == ov::element::Type_t::f16 || precision == ov::element::Type_t::bf16 ||
precision == ov::element::Type_t::i32,
"Unsupported precision ", precision.get_type_name());
}
cv::Mat in;
if (C == 3) {
if (colorFormat == "RGB") {
cv::cvtColor(cvImg, in, cv::COLOR_BGR2RGB);
} else {
in = cvImg;
}
} else {
if (colorFormat == "RGB") {
cv::cvtColor(cvImg, in, cv::COLOR_BGR2RGBA);
} else {
cv::cvtColor(cvImg, in, cv::COLOR_BGR2BGRA);
}
}
if (precision != ov::element::Type_t::u8) {
in.convertTo(in, CV_32F);
}
const auto pictureArea = static_cast<size_t>(in.size().area());
if (W * H > pictureArea) {
cv::resize(in, in, cv::Size(static_cast<int>(W), static_cast<int>(H)), 0.0, 0.0, cv::INTER_AREA);
} else {
cv::resize(in, in, cv::Size(static_cast<int>(W), static_cast<int>(H)), 0.0, 0.0, cv::INTER_LINEAR);
}
if (layout == ov::Layout("NHWC")) {
const auto dataBuffer = reinterpret_cast<uint8_t*>(tensor.data());
cv::Mat auxOut(static_cast<int>(H), static_cast<int>(W), cvType);
cv::Mat tensorOut(static_cast<int>(H), static_cast<int>(W), cvType, dataBuffer);
// only a first image from an input image array fills an original input tensor up.
// Subsequent images (if exist) will fill batch slices of the input tensor
// by its number in the input array respectively
cv::Mat &out = (cvImgInBatch.index == 0 ? tensorOut : auxOut);
if (precision == ov::element::Type_t::f16) {
const auto inPtr = in.ptr<float>();
const auto outPtr = out.ptr<ov::float16>();
convertBufferType(outPtr, inPtr, out.size().area() * C);
} else if (precision == ov::element::Type_t::bf16) {
const auto inPtr = in.ptr<float>();
const auto outPtr = out.ptr<ov::bfloat16>();
convertBufferType(outPtr, inPtr, out.size().area() * C);
} else if (precision == ov::element::Type_t::i32) {
in.convertTo(out, CV_32S);
} else {
in.copyTo(out);
}
// Being called sequentially with ascending `cvImgInBatch.index` value,
// it fills up rest of the batched tensor by
// a last requested image data until its ending from a batched slice position
// determined by parameter 'cvImgInBatch.index', so that filling N batched tensor
// by array of images size M, where M < N, will make up
// The final batched tensor will comprise
// [imgIdx_0, imgIdx_1,..., imgIdx_M, imgIdx_M,...,imgIdx_M] as its slices
if (cvImgInBatch.index == 0 && N != 1) {
std::cout << "Fill up all input batch slices up to " << N
<< " with image data from the array: ["
<< cvImgInBatch.to_string() << std::endl;
}
for (size_t n = std::max<size_t>(1, cvImgInBatch.index); n < N; ++n) {
if (n == std::max<size_t>(1, cvImgInBatch.index) && cvImgInBatch.index >= 1) {
std::cout << "Fill input batch slices starting from index "
<< n << " up to " << N << " with image data from the array: "
<< cvImgInBatch.to_string() << std::endl;
}
cv::Mat batch(static_cast<int>(H),
static_cast<int>(W),
cvType,
dataBuffer + n * (out.size().area() * out.elemSize()));
out.copyTo(batch);
}
} else if (layout == ov::Layout("NCHW")) {
ov::Tensor auxTensor(precision, shape);
ov::Tensor& outTensor = (cvImgInBatch.index == 0 ? tensor : auxTensor);
// only a first image from an input image array fills an original input tensor up.
// Subsequent images (if exist) will fill batch slices of the input tensor
// by its number in the input array respectively
auto tensorPlanes = ovToCV(outTensor, shape, layout, 0);
if (!(precision == ov::element::Type_t::f16 ||
precision == ov::element::Type_t::bf16)) {
cv::split(in, tensorPlanes);
} else {
std::vector<cv::Mat> inPlanes;
cv::split(in, inPlanes);
OPENVINO_ASSERT(tensorPlanes.size() == inPlanes.size());
for (size_t i = 0; i < tensorPlanes.size(); ++i) {
const auto inPtr = inPlanes[i].ptr<float>();
if (precision == ov::element::Type_t::f16) {
const auto outPtr = tensorPlanes[i].ptr<ov::float16>();
convertBufferType(outPtr, inPtr, inPlanes[i].size().area());
} else if (precision == ov::element::Type_t::bf16) {
const auto outPtr = tensorPlanes[i].ptr<ov::bfloat16>();
convertBufferType(outPtr, inPtr, inPlanes[i].size().area());
}
}
}
// Being called sequentially with ascending `cvImgInBatch.index` value,
// it fills up rest of the batched tensor by
// a last requested image data until its ending from a batched slice position
// determined by parameter 'cvImgInBatch.index', so that filling N batched tensor
// by array of images size M, where M < N, will make up
// The final batched tensor will comprise
// [imgIdx_0, imgIdx_1,..., imgIdx_M, imgIdx_M,...,imgIdx_M] as its slices
if (cvImgInBatch.index == 0 && N != 1) {
std::cout << "Fill up all input batch slices planes up to " << N
<< " with image data from the array: "
<< cvImgInBatch.to_string() << std::endl;
}
for (size_t n = std::max<size_t>(1, cvImgInBatch.index); n < N; ++n) {
if (n == std::max<size_t>(1, cvImgInBatch.index) && cvImgInBatch.index >= 1) {
std::cout << "Fill input batch slices planes starting from index "
<< n << " up to " << N << " with image data from the array: "
<< cvImgInBatch.to_string() << std::endl;
}
const auto batchPlanes = ovToCV(tensor, shape, layout, n);
OPENVINO_ASSERT(batchPlanes.size() == tensorPlanes.size());
for (size_t i = 0; i < tensorPlanes.size(); ++i) {
tensorPlanes[i].copyTo(batchPlanes[i]);
}
}
}
}
std::unordered_map<std::string, std::vector<float>> parseMeanOrScaleString(const std::string& mean_scale) {
std::unordered_map<std::string, std::vector<float>> result;
// Format: layer1[255,255,255],layer2[255,255,255] for particular layers,
// or [255,255,255] for all layers
std::string search_string = mean_scale;
auto start_pos = search_string.find_first_of('[');
while (start_pos != std::string::npos) {
auto end_pos = search_string.find_first_of(']');
if (end_pos == std::string::npos)
break;
auto input_name = search_string.substr(0, start_pos);
if (result.count(input_name) == 0) {
auto input_value_string = search_string.substr(start_pos + 1, end_pos - start_pos - 1);
result[input_name] = splitFloat(input_value_string, ',');
if (input_name.empty()) {
if (mean_scale != search_string) {
throw std::logic_error("Can't parse input parameter string: " + mean_scale +
". Format of value: layer1[255,255,255],layer2[255,255,255] "
"for particular layers, or just [255,255,255] for all layers.");
}
search_string = search_string.substr(end_pos + 1);
break;
}
} else {
throw std::logic_error("Specifying mean and scale for the same layer/s"
" more than once is prohibited: " +
mean_scale);
}
search_string = search_string.substr(end_pos + 1);
if (search_string.empty() || search_string.front() != ',')
break;
search_string = search_string.substr(1);
if (search_string.empty()) {
throw std::logic_error("Can't parse input parameter string: " + mean_scale +
". Format of value: layer1[255,255,255],layer2[255,255,255] "
"for particular layers, or just [255,255,255] for all layers.");
}
start_pos = search_string.find_first_of('[');
}
if (!search_string.empty())
throw std::logic_error("Can't parse input parameter string: " + mean_scale +
". Format of value: layer1[255,255,255],layer2[255,255,255] "
"for particular layers, or just [255,255,255] for all layers.");
return result;
}
std::vector<std::vector<float>> parseMeanOrScale(const std::string& mean_scale,
const std::vector<ov::Output<ov::Node>>& inputs_info) {
std::vector<std::vector<float>> result(inputs_info.size());
auto mean_or_scale_map = parseMeanOrScaleString(mean_scale);
for (auto&& [layer_name, mean_or_scale] : mean_or_scale_map) {
if (!layer_name.empty()) {
// Add an explicit reference. Lambda expressions in C++17 cannot capture structured bindings.
const auto& layer_name_ref = layer_name;
auto required_input_it = std::find_if(inputs_info.begin(), inputs_info.end(),
[&layer_name_ref](const ov::Output<const ov::Node>& item) {
return item.get_any_name() == layer_name_ref;
});
if (required_input_it != inputs_info.end()) {
result[std::distance(inputs_info.begin(), required_input_it)] = mean_or_scale;
} else {
throw std::logic_error(std::string("Input with name '") + layer_name + "' doesn't exist.");
}
} else {
for (size_t idx = 0; idx < inputs_info.size(); ++idx) {
result[idx] = mean_or_scale;
}
}
}
return result;
}
using RegexPtr = std::unique_ptr<std::regex>;
std::map<RegexPtr, ov::Layout> parseLayoutRegex(std::string layouts) {
const std::string original_layouts = layouts; // Keep copy for error message
std::map<std::string, std::string> input_output_layouts = parseArgMap(std::move(layouts));
std::map<RegexPtr, ov::Layout> out;
for (const auto& input_output_layout : input_output_layouts) {
auto [name, value] = input_output_layout;
if (value.empty()) {
if (name.empty()) {
throw std::runtime_error("Can't parse layouts string \"" + original_layouts +
"\" into valid \"input:layout;input:layout\" pairs");
}
// there is no value only name, thus we consider input/output name as "any" and
// apply layout value as the parsed name
out.emplace(std::make_unique<std::regex>(".*"), name);
continue;
}
std::string valid_regex_str = name.empty() ? ".*" : "^" + name + "$";
out.emplace(std::make_unique<std::regex>(std::move(valid_regex_str)), std::move(value));
}
return out;
}
/**
* @brief Parses and processes input files and matches them to model input names.
*
* This function processes input file specifications for multiple test cases. It supports both
* the simple format (same file for all inputs) and the mapped format (specific files for specific inputs).
*
* The input format supports:
* - Multiple test cases separated by semicolons (';')
* - Within each test case, input mappings separated by commas (',')
* - Optional batched inputs separated by pipe ('|') are ignored
* - Each mapping in the format "input_name:file_path1|file_path2"
*
* @param inputsInfo Vector of model input information objects (retrieved from ov::Model::inputs())
* @param inputCases String containing input file specifications
*
* @return A string with processed input files, maintaining the test case structure (semicolon-separated)
* with each test case containing comma-separated input files.
*
* @throws OpenVINO::AssertionFailure If input specification is incomplete or contains duplicates within the
* same test case.
*/
std::string parseInputFiles(const std::vector<ov::Output<const ov::Node>> inputsInfo, const std::string& inputCases) {
// Splits input files into test cases (delimited by ';')
std::vector<std::string> inputCasesList = splitStringList(inputCases, ';');
std::vector<std::string> processedInputCasesList(inputCasesList.size());
for (size_t testCaseIndex = 0; testCaseIndex < inputCasesList.size(); ++testCaseIndex) {
const auto& inputFilesPerCase = inputCasesList[testCaseIndex];
std::map<std::string, std::string> inputFilesPerCaseMap = parseArgMap(inputFilesPerCase, ',');
std::vector<std::string> processedInputFilesPerCaseList(inputsInfo.size());
for (size_t i = 0; i < inputsInfo.size(); ++i) {
const auto& inputInfo = inputsInfo[i];
const auto& inputNames = inputInfo.get_names();
for (const auto& name : inputNames) {
auto it = inputFilesPerCaseMap.find(name);
if (it != inputFilesPerCaseMap.end()) {
processedInputFilesPerCaseList[i] = it->second;
break;
}
}
}
size_t valueCount = std::count_if(processedInputFilesPerCaseList.begin(), processedInputFilesPerCaseList.end(),
[](const std::string& s) { return !s.empty(); });
// All inputs must have values or none must have values
if (valueCount > 0 && valueCount < inputsInfo.size()) {
OPENVINO_ASSERT(false, "Incomplete input specification. All inputs must be specified or none. "
"Check if there are duplicate input names in the input file map.");
}
if (valueCount == 0) {
processedInputCasesList[testCaseIndex] = inputFilesPerCase;
continue;
}
// Concatenate processedInputFilesPerCaseList results with , delimiter, then store in processedInputCasesList at index
std::string processedInputFilesPerCase;
for (size_t i = 0; i < processedInputFilesPerCaseList.size(); ++i) {
if (i > 0) {
processedInputFilesPerCase += ",";
}
processedInputFilesPerCase += processedInputFilesPerCaseList[i];
}
processedInputCasesList[testCaseIndex] = std::move(processedInputFilesPerCase);
}
// Concatenate processedInputCasesList results with ; delimiter
std::string processedInputCases;
for (size_t i = 0; i < processedInputCasesList.size(); ++i) {
if (i > 0) {
processedInputCases += ";";
}
processedInputCases += processedInputCasesList[i];
}
return processedInputCases;
}
template <class T>
std::optional<T> getRegexSubstitutionIfExist(const std::string& haystack, const std::map<RegexPtr, T>& substitutions) {
for (const auto& s : substitutions) {
if (std::regex_search(haystack, *s.first)) {
return {s.second};
}
}
return {};
}
//
// File utils
//
bool hasLoadableExt(const std::string& network_path) {
static const std::array<const char*, 5> ext_support_table{"xml", "onnx", "pdmodel", "pb", "tflite"};
return std::any_of(ext_support_table.begin(), ext_support_table.end(), [&network_path](const char* ext) {
static constexpr const auto dot_symbol = '.';
auto pos = network_path.rfind(dot_symbol);
std::string ext_name = {};
if (pos != std::string::npos)
ext_name = network_path.substr(pos + 1);
return strEq(ext_name, ext);
});
}
std::string cleanName(std::string name) {
std::replace_if(
name.begin(), name.end(),
[](unsigned char c) {
return !std::isalnum(c);
},
'_');
return name;
}
ov::Tensor loadImages(const ov::element::Type& precision, const ov::Shape& shape, const ov::Layout& layout,
const std::vector<std::string>& filePaths, const std::string& colorFormat) {
ov::Tensor tensor(precision, shape);
for (size_t fileIndex = 0; fileIndex != filePaths.size(); fileIndex++) {
const auto &filePath = filePaths[fileIndex];
const auto frame = cv::imread(filePath, cv::IMREAD_COLOR);
OPENVINO_ASSERT(!frame.empty(), "Failed to open input image file ", filePath);
cvToOV(frame, BatchIndexer{fileIndex, filePaths.size()}, tensor, shape, layout, colorFormat);
}
return tensor;
}
void loadBinary(const std::string& filePath, const BatchIndexer &fileSourceInBatch, ov::Tensor &requestedTensor,
const ov::element::Type& modelPrecision, const ov::Shape& shape,
const ov::Layout& layout, const ov::element::Type& dataPrecision) {
std::ifstream binaryFile(filePath, std::ios_base::binary | std::ios_base::ate);
OPENVINO_ASSERT(binaryFile, "Failed to open input binary file: ", filePath);
const auto fileSize = binaryFile.tellg();
binaryFile.seekg(0, std::ios_base::beg);
OPENVINO_ASSERT(binaryFile.good(), "While reading a file an error is encountered");
const size_t fileBytes = static_cast<size_t>(fileSize);
const size_t reqTensorBytes = static_cast<size_t>(requestedTensor.get_byte_size());
if (dataPrecision != modelPrecision && dataPrecision != ov::element::Type_t::dynamic) {
std::cout << "Converting " << filePath << " input from " << dataPrecision << " to " << modelPrecision
<< std::endl;
ov::Tensor inputTensor(dataPrecision, shape);
if (fileBytes == inputTensor.get_byte_size()) {
binaryFile.read(reinterpret_cast<char*>(inputTensor.data()), static_cast<std::streamsize>(fileBytes));
npu::utils::convertTensorPrecision(inputTensor, requestedTensor);
} else {
std::cout << "File contains " << fileBytes
<< " bytes, but it expected to be: " << inputTensor.get_byte_size()
<< " while converting precision from " << dataPrecision << " to " << modelPrecision
<< ". Check whether it is possible to fit it into batch loading " << std::endl;
OPENVINO_ASSERT(ov::layout::has_batch(layout),
"Input layout has no batch dimension: ", layout.to_string());
size_t N = shape[ov::layout::batch_idx(layout)];
OPENVINO_ASSERT(fileBytes * N == inputTensor.get_byte_size(), "File contains ", fileBytes, " bytes, but ",
inputTensor.get_byte_size() * N, " total in batch size ", N,
" expected while converting precision from ", dataPrecision, " to ", modelPrecision);
ov::Shape debatchedInputTensorShape(shape);
debatchedInputTensorShape[ov::layout::batch_idx(layout)] = 1;
ov::Tensor inputDebatchedTensor(dataPrecision, debatchedInputTensorShape);
binaryFile.read(reinterpret_cast<char*>(inputDebatchedTensor.data()),
static_cast<std::streamsize>(fileBytes));
ov::Tensor convertedPrecisionTensor(modelPrecision, debatchedInputTensorShape);
npu::utils::convertTensorPrecision(inputDebatchedTensor, convertedPrecisionTensor);
std::list<ov::Tensor> tensorsToJoin;
std::list<ov::Tensor> tensorsFromSplit = npu::utils::splitBatchedTensor(requestedTensor, layout, N);
// Constitute a new bathed tensor of size N from parts of it
// enumerated by indices from the interval [0...fileSourceInBatch.index],
// where fileSourceInBatch.index < N
// The rest parts of the new tensor [fileSourceInBatch.index+1...N]
// will be filled up by same content of an image of `fileSourceInBatch.index`
std::copy_n(tensorsFromSplit.begin(), std::min(fileSourceInBatch.index, N), std::back_inserter(tensorsToJoin));
if (fileSourceInBatch.index < N) {
std::generate_n(std::back_inserter(tensorsToJoin), N - fileSourceInBatch.index, [&convertedPrecisionTensor]() {
return convertedPrecisionTensor;
});
}
requestedTensor = npu::utils::joinTensors(tensorsToJoin, layout);
}
} else {
if (fileBytes == reqTensorBytes) {
OPENVINO_ASSERT(reqTensorBytes <= static_cast<size_t>(std::numeric_limits<std::streamsize>::max()),
"Requested tensor size is too big to convert to signed streamsize: ", reqTensorBytes);
binaryFile.read(reinterpret_cast<char*>(requestedTensor.data()),
static_cast<std::streamsize>(reqTensorBytes));
} else {
std::cout << "File contains " << fileBytes << " bytes, but it expected to be: " << reqTensorBytes
<< " when datatypes match. "
<< "Check whether it is possible to fit it into batch loading " << std::endl;
OPENVINO_ASSERT(ov::layout::has_batch(layout),
"Input layout has no batch dimension: ", layout.to_string());
size_t N = shape[ov::layout::batch_idx(layout)];
OPENVINO_ASSERT(fileBytes * N == reqTensorBytes, "File contains ", fileBytes, " bytes, but ",
reqTensorBytes, " in batch size ", N, " expected");
if (fileSourceInBatch.index == 0 && N != 1) {
std::cout << "Fill up all input batch slices up to " << N
<< " with binary data from the array: "
<< fileSourceInBatch.to_string() << std::endl;
}
for (size_t n = std::max<size_t>(0, fileSourceInBatch.index); n < N; ++n) {
if (n == std::max<size_t>(1, fileSourceInBatch.index) && fileSourceInBatch.index >= 1) {
std::cout << "Fill input batch slices starting from index "
<< n << " up to " << N
<< " with binary data from the data sources array: "
<< fileSourceInBatch.to_string() << std::endl;
}
binaryFile.seekg(0, std::ios_base::beg);
binaryFile.read(reinterpret_cast<char*>(requestedTensor.data()) + fileBytes * n,
static_cast<std::streamsize>(fileBytes));
}
}
}
}
ov::Tensor loadBinaries(const ov::element::Type& modelPrecision, const ov::Shape& shape, const ov::Layout& layout,
const std::vector<std::string>& filePaths, const ov::element::Type& dataPrecision) {
ov::Tensor requestedTensor(modelPrecision, shape);
for (size_t fileIndex = 0; fileIndex != filePaths.size(); fileIndex++) {
const auto &filePath = filePaths[fileIndex];
loadBinary(filePath, BatchIndexer{fileIndex, filePaths.size()}, requestedTensor, modelPrecision, shape, layout, dataPrecision);
}
return requestedTensor;
}
/**
* @brief Loads the contents of a locally stored file inside an OpenVINO tensor intended to be used as input in the
* context of the application.
* @details The data being loaded can either be an image or a binary file, the switch between these cases can be
* performed by setting the "img_as_bin" flag accordingly. If an image is being loaded, the OpenCV library is deployed
* for reading followed by a conversion to the OpenVINO format. If a binary file is loaded, the content's type is
* converted from "dataPrecision" to "modelPrecision" before constructing the tensor.
*
* @param modelPrecision The precision accepted by the model's input
* @param shape The shape accepted by the model's input
* @param layout The layout used by the model's input
* @param filePath Indicates the location of the file to be loaded
* @param colorFormat Indicates the color format only in the case when an image is being loaded.
* @param dataPrecision Indicates the precision used by the data found within the binary file.
* @return The tensor containing the loaded data.
*/
ov::Tensor loadInput(const ov::element::Type& modelPrecision,
const ov::Shape& shape,
const ov::Layout& layout,
const std::vector<std::string>& filePaths,
const std::string& colorFormat,
const ov::element::Type& dataPrecision = ov::element::Type_t::dynamic) {
if (isImage(shape, layout) && !FLAGS_img_as_bin) {
return loadImages(modelPrecision, shape, layout, filePaths, colorFormat);
} else {
return loadBinaries(modelPrecision, shape, layout, filePaths, dataPrecision);
}
}
ov::Tensor loadTensor(const ov::element::Type& precision, const ov::Shape& shape, const std::string& filePath) {
ov::Tensor tensor(precision, shape);
std::ifstream file(filePath, std::ios_base::in | std::ios_base::binary);
OPENVINO_ASSERT(file.is_open(), "Can't open file ", filePath, " for read");
const auto dataBuffer = reinterpret_cast<char*>(tensor.data());
OPENVINO_ASSERT(tensor.get_byte_size() <= static_cast<size_t>(std::numeric_limits<std::streamsize>::max()),
"Tensor size is too big to convert to signed streamsize: ", tensor.get_byte_size());
file.read(dataBuffer, static_cast<std::streamsize>(tensor.get_byte_size()));
return tensor;
}
void dumpTensor(const ov::Tensor& tensor, const std::string& filePath) {
std::ofstream file(filePath, std::ios_base::out | std::ios_base::binary);
OPENVINO_ASSERT(file.is_open(), "Can't open file ", filePath, " for write");
const auto dataBuffer = reinterpret_cast<const char*>(tensor.data());
OPENVINO_ASSERT(tensor.get_byte_size() <= static_cast<size_t>(std::numeric_limits<std::streamsize>::max()),
"Tensor size is too big to convert to signed streamsize: ", tensor.get_byte_size());
file.write(dataBuffer, static_cast<std::streamsize>(tensor.get_byte_size()));
}
std::map<std::string, std::string> parseConfigFile() {
std::map<std::string, std::string> config;
std::ifstream file(FLAGS_config);
OPENVINO_ASSERT(file.is_open(), "Can't open file ", FLAGS_config, " for read");
std::string option;
while (std::getline(file, option)) {
if (option.empty() || option[0] == '#') {
continue;
}
size_t spacePos = option.find_first_of(" \t\n\r");
OPENVINO_ASSERT(spacePos != std::string::npos,
"Invalid config parameter format. Space separator required here: ", option);
std::string key, value;
if (spacePos != std::string::npos) {
key = option.substr(0, spacePos);
size_t valueStart = option.find_first_not_of(" \t\n\r", spacePos);
OPENVINO_ASSERT(valueStart != std::string::npos,
"An invalid config parameter value detected, it mustn't be empty: ", option);
size_t valueEnd = option.find_last_not_of(" \t\n\r");
value = option.substr(valueStart, valueEnd - valueStart + 1);
config[key] = value;
}
}
return config;
}
ov::AnyMap buildDeviceConfig() {
ov::AnyMap config;
if (!FLAGS_log_level.empty()) {
config[ov::log::level.name()] = FLAGS_log_level;
}
if (FLAGS_device == "CPU") {
config["LP_TRANSFORMS_MODE"] = std::string("NO");
}
if (FLAGS_pc) {
config[ov::enable_profiling.name()] = true;
}
if (!FLAGS_config.empty()) {
const auto fileConfigs = parseConfigFile();
for (const auto& [key, value] : fileConfigs) {
config[key] = value;
}
}
return config;
}
// This function formats performance counters in a same way as benchmark_app -pc does.
// It is a copy-paste from $OPENVINO_HOME/samples/cpp/common/utils/include/samples/common.hpp
using ProfVec = std::vector<ov::ProfilingInfo>;
static void printPerformanceCounts(ProfVec performanceData, std::ostream& stream, std::string deviceName,
bool bshowHeader = true) {
std::chrono::microseconds totalTime = std::chrono::microseconds::zero();
// Print performance counts
if (bshowHeader) {
stream << std::endl << "performance counts:" << std::endl << std::endl;
}
std::ios::fmtflags fmt(std::cout.flags());
for (const auto& it : performanceData) {
std::string toPrint(it.node_name);
const int maxLayerName = 30;
if (it.node_name.length() >= maxLayerName) {
toPrint = it.node_name.substr(0, maxLayerName - 4);
toPrint += "...";
}
stream << std::setw(maxLayerName) << std::left << toPrint;
switch (it.status) {
case ov::ProfilingInfo::Status::EXECUTED:
stream << std::setw(15) << std::left << "EXECUTED";
break;
case ov::ProfilingInfo::Status::NOT_RUN:
stream << std::setw(15) << std::left << "NOT_RUN";
break;
case ov::ProfilingInfo::Status::OPTIMIZED_OUT:
stream << std::setw(15) << std::left << "OPTIMIZED_OUT";
break;
}
stream << std::setw(30) << std::left << "layerType: " + std::string(it.node_type) + " ";
stream << std::setw(20) << std::left << "realTime: " + std::to_string(it.real_time.count());
stream << std::setw(20) << std::left << "cpu: " + std::to_string(it.cpu_time.count());
stream << " execType: " << it.exec_type << std::endl;
if (it.real_time.count() > 0) {
totalTime += it.real_time;
}
}
stream << std::setw(20) << std::left << "Total time: " + std::to_string(totalTime.count()) << " microseconds"
<< std::endl;
std::cout << std::endl;
std::cout << "Full device name: " << deviceName << std::endl;
std::cout << std::endl;
std::cout.flags(fmt);
}
bool checkBBoxOutputs(std::vector<utils::BoundingBox>& actualOutput, std::vector<utils::BoundingBox>& refOutput,
const size_t imgWidth, const size_t imgHeight, const float boxTolerance,
const float probTolerance) {
std::cout << "Ref Top:" << std::endl;
for (size_t i = 0; i < refOutput.size(); ++i) {
const auto& bb = refOutput[i];
std::cout << i << " : " << bb.idx << " : [(" << bb.left << " " << bb.top << "), (" << bb.right << " "
<< bb.bottom << ")] : " << bb.prob * 100 << "%" << std::endl;
}
std::cout << "Actual top:" << std::endl;
for (size_t i = 0; i < actualOutput.size(); ++i) {
const auto& bb = actualOutput[i];
std::cout << i << " : " << bb.idx << " : [(" << bb.left << " " << bb.top << "), (" << bb.right << " "
<< bb.bottom << ")] : " << bb.prob * 100 << "%" << std::endl;
}
for (const auto& refBB : refOutput) {
bool found = false;
float maxBoxError = 0.0f;
float maxProbError = 0.0f;
for (const auto& actualBB : actualOutput) {
if (actualBB.idx != refBB.idx) {
continue;
}
const utils::Box actualBox{actualBB.left / imgWidth, actualBB.top / imgHeight,
(actualBB.right - actualBB.left) / imgWidth,
(actualBB.bottom - actualBB.top) / imgHeight};
const utils::Box refBox{refBB.left / imgWidth, refBB.top / imgHeight, (refBB.right - refBB.left) / imgWidth,
(refBB.bottom - refBB.top) / imgHeight};
const auto boxIntersection = boxIntersectionOverUnion(actualBox, refBox);
const auto boxError = 1.0f - boxIntersection;
maxBoxError = std::max(maxBoxError, boxError);
const auto probError = std::fabs(actualBB.prob - refBB.prob);
maxProbError = std::max(maxProbError, probError);
if (boxError > boxTolerance) {
continue;
}
if (probError > probTolerance) {
continue;
}
found = true;
break;
}
if (!found) {
std::cout << "maxBoxError=" << maxBoxError << " "
<< "maxProbError=" << maxProbError << std::endl;
return false;
}
}
return true;
}
// FIXME: User must provide layout explicitly.
// No "default" layout for IRv11 models.
static ov::Layout getLayoutByRank(const size_t rank) {
switch (rank) {
case 0:
return ov::Layout::scalar();
case 1:
return ov::Layout("C");
case 2:
return ov::Layout("NC");
case 3:
return ov::Layout("CHW");
case 4:
return ov::Layout("NCHW");
case 5:
return ov::Layout("NCDHW");
}
throw std::logic_error("Failed to get layout for rank equal to " + std::to_string(rank));
}
static std::string toString(const std::vector<size_t>& vec) {
std::stringstream ss;
if (!vec.empty()) {
ss << "[";
for (size_t i = 0; i < vec.size() - 1; ++i) {
ss << vec[i] << ",";
}
ss << vec[vec.size() - 1];
ss << "]";
} else {
ss << "SCALAR";
}
return ss.str();
}
/**
* @brief This class is designed to gather and manage layout-related information and hints.
* It consolidates various layout parameters such as user-defined layouts, model-defined layouts, etc.
* which are provided as command-line arguments.
* @details As you can see there are several layout-affiliated parameters among the command line arguments:
* user-defined layout, model-defined layout etc. To maintain a consistent user experience,
* the single-image-test does not require explicit layout specification at the moment.
* Instead, it uses auto-deduction for the layout based on a shape ranks, as implemetned in
* the @getLayoutByRank function. While this approach works for a majority of models,
* it may fail for certain edge cases, leading to incorrect layout deductions.
* This can cause misinterpretation of the batch dimension, resulting in errors during
* the blob comparison process.
* The class provides two important methods: @getDeterministicLayout and @getAnyLayout, which
* are used by single-image-test in the comparison process with a different level of trust.
* If any layouts is provied by the user through command-line agruments, it is treated as deterministic,
* and @getDeterministicLayout returns either theuser-specified layout for tensors or
* the user-specified layout for the model.
* If none of these layouts are provided, then @getDeterministicLayout returns nothing and the
* auto-deducted layout will be returned from @getAnyLayout function. Contrary, if anyone from
* deterministic layout set is provided,the fucntion @getAnyLayout will behave the same as @getDeterministicLayout
*
*
* @example Consider a batched resnet50 with N=2,which results in a result blob containing 2000 elements.
* In this case:
* 1000 elements belongs to part [1/2] of the blob
* another 1000 elements to the second part [2/2] of the initial batched blob.
*
* If we compare these result blobs in non-batched mode (where the layout is unspecified),
* we extract Tthe OP_K elements from the entire 2000-element blob. However,
* if the classification probabilities for parts [1/2] and [2/2] differ significantly, say:
* Part [1/2] has classes with probabilities in the range [15..20]
* Part [2/2] has classes with probabilities in the range [9..14]
*
* Then the TOP_K tests classes will be constituted from elements of the part [1/2] only.
* Consequently, the results from part [2/2] will not be involved as parameters to validate
* in that classification process. Additionally, slightly different blobs
* may give us comparison mismatch even if they all fit with a requested probability_tolerance.
*
* @param tensorLayout The layout specified by user for tensors
* @param modelLayout The layout specified by user for a model
* @param autoDeductedLayout The layout determined from shape
*/
class LayoutDescription {
std::optional<ov::Layout> tensorLayout;
std::optional<ov::Layout> modelLayout;
ov::Layout autoDeductedLayout;
LayoutDescription(std::optional<ov::Layout>&& userLayout,
std::optional<ov::Layout>&& modelLayout,
ov::Layout&& deductedLayout)
: tensorLayout(std::move(userLayout)),
modelLayout(std::move(modelLayout)),
autoDeductedLayout(std::move(deductedLayout)) {}
public:
~LayoutDescription() = default;
LayoutDescription(const LayoutDescription&) = default;
LayoutDescription(LayoutDescription&&) = default;
LayoutDescription& operator=(const LayoutDescription&) = default;
LayoutDescription& operator=(LayoutDescription&&) = default;
bool hasDeterministicLayout() const {
return tensorLayout.has_value() || modelLayout.has_value();
}
const ov::Layout& getDeterministicLayout() const {
if (tensorLayout.has_value()) {
return tensorLayout.value();
}
if (modelLayout.has_value()) {
return modelLayout.value();
}
throw std::invalid_argument("LayoutDescription has no any deterministic layout");
}
ov::Layout getAnyLayout() const {
// prefer deterministica layouts over the auto-deducted
return hasDeterministicLayout() ? getDeterministicLayout() : autoDeductedLayout;
}
static LayoutDescription create(const std::string& inputOutputName,
const std::map<RegexPtr, ov::Layout>& userDefinedLayouts,
const std::map<RegexPtr, ov::Layout>& modelLayouts,
const ov::Shape& shape) {
std::optional<ov::Layout> userLayout = getRegexSubstitutionIfExist(inputOutputName, userDefinedLayouts);
std::optional<ov::Layout> modelLayout = getRegexSubstitutionIfExist(inputOutputName, modelLayouts);
auto deductedLayout = getLayoutByRank(shape.size());
if (!userLayout.has_value() && !modelLayout.has_value()) {
std::cout << "WARNING: Since --oml option isn't set, output model layout for layer \"" << inputOutputName
<< "\" is infered from shape: " << toString(shape) << " rank (" << shape.size() << ") as "
<< deductedLayout.to_string() << std::endl;
}
return LayoutDescription{std::move(userLayout), std::move(modelLayout), std::move(deductedLayout)};
}
};
using LayoutMap = std::unordered_map<std::string, LayoutDescription>;
std::unordered_map<std::string, ov::Layout> transformLayoutDescriptionToAnyLayoutsMap(const LayoutMap& layoutDescrMap) {
std::unordered_map<std::string, ov::Layout> ret;
for (auto [name, description] : layoutDescrMap) {
ret[name] = description.getAnyLayout();
}
return ret;
}
size_t getTensorBatchSize(const ov::Tensor& tensor, const std::string& tensorName, const LayoutMap& outputLayouts) {
// calculate batch_size by taking into account only deterministic layout information
// We cannot rely on the layout deducted from a shape, as it is incorrect in majority of cases
size_t batch_size = 1;
if (auto it = outputLayouts.find(tensorName); it != outputLayouts.end()) {
const LayoutDescription& description = it->second;
if (description.hasDeterministicLayout()) {
const ov::Layout& layout = description.getDeterministicLayout();
if (ov::layout::has_batch(layout)) {
batch_size = tensor.get_shape()[ov::layout::batch_idx(layout)];
}
}
}
return batch_size;
}
std::list<ov::Tensor> splitBatchedTensor(const ov::Tensor& tensor,
const std::string& tensorName,
const LayoutMap& outputLayouts) {
std::list<ov::Tensor> outputDebatchedTensors;
size_t batch_size = getTensorBatchSize(tensor, tensorName, outputLayouts);
if (batch_size == 1) {
outputDebatchedTensors.push_back(tensor);
} else {
OPENVINO_ASSERT(outputLayouts.find(tensorName) != outputLayouts.end());
outputDebatchedTensors =
npu::utils::splitBatchedTensor(tensor,
outputLayouts.find(tensorName)->second.getDeterministicLayout(),
batch_size);
}
return outputDebatchedTensors;
}
using BlobTestMethod = std::function<bool(const ov::Tensor&, const ov::Tensor&)>;
bool test_blobs_in_batch(const std::string& tensorName,
const std::list<ov::Tensor>& outputDebatchedTensors,
const std::list<ov::Tensor>& referenceDebatchedTensors,
BlobTestMethod testTensors) {
OPENVINO_ASSERT(referenceDebatchedTensors.size() == outputDebatchedTensors.size());
auto [batch, batchBundleSize] = std::make_tuple(0, outputDebatchedTensors.size());
auto referenceDebatchedTensorIterator = referenceDebatchedTensors.begin();
for (auto outputDebatchedTensorIterator = outputDebatchedTensors.begin();
outputDebatchedTensorIterator != outputDebatchedTensors.end();
++outputDebatchedTensorIterator, ++referenceDebatchedTensorIterator, ++batch) {
if (batchBundleSize != 1) {
std::cout << "Compare \"" << tensorName << "\"(" << batch << "/" << batchBundleSize
<< " batch) with reference" << std::endl;
} else {
std::cout << "Compare \"" << tensorName << "\" with reference" << std::endl;
}
if (!testTensors(*outputDebatchedTensorIterator, *referenceDebatchedTensorIterator)) {
return false;
}
}
return true;
}
//
// Classification mode
//
std::vector<std::pair<int, float>> parseClassification(const float* dataBuffer, size_t dataBufferElementsCount) {
OPENVINO_ASSERT(dataBuffer != nullptr, "Received a tensor with no allocated buffer");
std::vector<std::pair<int, float>> res(dataBufferElementsCount);
for (size_t i = 0; i < dataBufferElementsCount; ++i) {
res[i].first = static_cast<int>(i);
res[i].second = dataBuffer[i];
}
std::sort(res.begin(), res.end(), [](const std::pair<int, float>& a, const std::pair<int, float>& b) {
return a.second > b.second;
});
return res;
}
std::vector<std::vector<std::pair<int, float>>> parseClassificationBatch(const ov::Tensor& tensor, size_t batch_size) {
OPENVINO_ASSERT(batch_size, "batch_size can't be 0");
OPENVINO_ASSERT(tensor.get_element_type() == ov::element::Type_t::f32,
"Unsupported precision: ", tensor.get_element_type().get_type_name());
std::vector<std::vector<std::pair<int, float>>> ret;
const float* dataBuffer = tensor.data<const float>();
OPENVINO_ASSERT(dataBuffer != nullptr, "Received a tensor with no allocated buffer");
size_t batch_bundle_size = tensor.get_size() / batch_size;
OPENVINO_ASSERT(!(tensor.get_size() % batch_bundle_size),
"Tensor is a not batched tensor! Size: ", tensor.get_size(),
" can't be batched on a batch size: ", batch_size, " properly");
size_t i = 0;
for (; i < tensor.get_size(); i += batch_bundle_size) {
if (batch_size != 1) {
std::cout << "restore tensor from data bundle: (" << i << "/" << tensor.get_size() << " bytes)"
<< std::endl;
}
ret.push_back(parseClassification(dataBuffer + i, batch_bundle_size));
}
OPENVINO_ASSERT(i == tensor.get_size());
return ret;
}
bool testClassification(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
OPENVINO_ASSERT(outputs.size() == 1);
OPENVINO_ASSERT(outputs.size() == references.size());
const ov::Tensor outputFP32 = npu::utils::toFP32(outputs.begin()->second);
const ov::Tensor referenceFP32 = npu::utils::toFP32(references.begin()->second);
OPENVINO_ASSERT(outputFP32.get_element_type() == referenceFP32.get_element_type());
OPENVINO_ASSERT(outputFP32.get_shape() == referenceFP32.get_shape());
OPENVINO_ASSERT(referenceFP32.get_element_type() == ov::element::Type_t::f32);
size_t batch_size = getTensorBatchSize(outputFP32, outputs.begin()->first, outputLayouts);
auto probsBatch = parseClassificationBatch(outputFP32, batch_size);
auto refProbsBatch = parseClassificationBatch(referenceFP32, batch_size);
OPENVINO_ASSERT(refProbsBatch.size() == probsBatch.size(),
"Incorrect batch size of both output tensor: ", probsBatch.size(),
" and reference tensor: ", refProbsBatch.size(), ". Expected: ", batch_size);
for (size_t i = 0; i < batch_size; i++) {
OPENVINO_ASSERT(probsBatch[i].size() == refProbsBatch[i].size(),
"Incorrect size of referenced tensor in batch bundle number: (", i, "/", batch_size, ")",
". Expected size: ", probsBatch[i].size(), ", got: ", refProbsBatch[i].size());
OPENVINO_ASSERT(refProbsBatch[i].size() >= FLAGS_top_k);
refProbsBatch[i].resize(FLAGS_top_k);
}
// Parse prob_tolerance (can be per-layer or global)
auto toleranceMap = utils::parsePerLayerValues(FLAGS_prob_tolerance, metric_defaults::prob_tolerance);
double probTolerance = utils::getValueForLayer(toleranceMap, outputs.begin()->first);
bool result = true;
for (size_t i = 0; i < probsBatch.size(); i++) {
if (batch_size != 1) {
std::cout << "Check tensor bundle: (" << i << "/" << batch_size << " batch)" << std::endl;
}
auto probs = probsBatch[i];
const auto& refs = refProbsBatch[i];
OPENVINO_ASSERT(probs.size() >= FLAGS_top_k);
probs.resize(FLAGS_top_k);
std::cout << "Actual top:" << std::endl;
for (size_t j = 0; j < probs.size(); ++j) {
std::cout << " " << j << " : " << probs[j].first << " : " << probs[j].second << std::endl;
}
std::cout << "Ref Top:" << std::endl;
for (size_t j = 0; j < refs.size(); ++j) {
std::cout << " " << j << " : " << refs[j].first << " : " << refs[j].second << std::endl;
}
for (const auto& refElem : refs) {
const auto actualIt =
std::find_if(probs.cbegin(), probs.cend(), [&refElem](const std::pair<int, float>& arg) {
return refElem.first == arg.first;
});
if (actualIt == probs.end()) {
std::cout << "Ref result " << refElem.first << " was not found in actual results" << std::endl;
result = result && false;
continue;
}
const auto& actualElem = *actualIt;
if (refElem.second > actualElem.second) {
const auto probDiff = std::fabs(refElem.second - actualElem.second);
if (probDiff > probTolerance) {
std::cout << "Probability value mismatch for " << refElem.first << " : " << refElem.second << " vs "
<< actualElem.second << std::endl;
result = result && false;
}
}
}
}
return result;
}
//
// RAW mode
// e.g. '--mode raw --raw_tolerance "layer1:0.01;layer2:0.02"'
//
bool compareRAW(const ov::Tensor& output, const ov::Tensor& reference, double tolerance) {
if (output.get_shape() != reference.get_shape()) {
std::cout << "Output and reference tensors have different shapes" << std::endl;
return false;
}
const ov::Tensor outputFP32 = npu::utils::toFP32(output);
const ov::Tensor referenceFP32 = npu::utils::toFP32(reference);
const auto outputBuffer = outputFP32.data<const float>();
const auto referenceBuffer = referenceFP32.data<const float>();
const auto totalCount = referenceFP32.get_size();
const auto printCount = std::min<size_t>(totalCount, 10);
for (size_t i = 0; i < totalCount; ++i) {
const auto referenceValue = referenceBuffer[i];
const auto outputValue = outputBuffer[i];
const auto absDiff = std::fabs(referenceValue - outputValue);
if (i < printCount) {
std::cout << " " << i << " :"
<< " ref : " << std::setw(10) << referenceValue << " output : " << std::setw(10) << outputValue
<< " absdiff : " << std::setw(10) << absDiff << std::endl;
}
if (absDiff > tolerance) {
std::cout << "Absolute difference between output value " << outputValue << " and reference value "
<< referenceValue << " at index " << i << " larger then tolerance" << std::endl;
return false;
}
}
return true;
}
bool testRAW(const TensorMap& outputTensors, const TensorMap& referenceTensors, const LayoutMap& outputLayouts) {
if (outputTensors.size() != referenceTensors.size()) {
std::cout << "The number of predicted outputs differ from the number of references" << std::endl;
return false;
}
// Parse per-layer thresholds
auto toleranceMap = utils::parsePerLayerValues(FLAGS_raw_tolerance, metric_defaults::raw_tolerance);
bool allPassed = true;
for (const auto& [tensorName, outputTensor] : outputTensors) {
auto referenceTensorIterator = referenceTensors.find(tensorName);
OPENVINO_ASSERT(referenceTensorIterator != referenceTensors.end());
// Get tolerance for this specific layer
double layerTolerance = utils::getValueForLayer(toleranceMap, tensorName);
BlobTestMethod blobComparator = [layerTolerance](ov::Tensor outputTensor, ov::Tensor referenceTensor) {
return compareRAW(outputTensor, referenceTensor, layerTolerance);
};
if (!test_blobs_in_batch(tensorName,
splitBatchedTensor(outputTensor, tensorName, outputLayouts),
splitBatchedTensor(referenceTensorIterator->second, tensorName, outputLayouts),
blobComparator)) {
allPassed = false;
}
}
return allPassed;
}
//
// Cosine-Similarity mode
// (using 'cosim_threshold' flag, with expected value in range [0.0 -> 1.0])
// e.g. '--mode cosim --cosim_threshold 0.98'
// e.g. '--mode cosim --cosim_threshold "layer1:0.98;layer2:0.95"'
//
bool compareCoSim(const ov::Tensor& output, const ov::Tensor& reference, double threshold) {
if (output.get_shape() != reference.get_shape()) {
std::cout << "Actual and reference blobs has different shape" << std::endl;
return false;
}
const ov::Tensor outputFP32 = npu::utils::toFP32(output);
const ov::Tensor referenceFP32 = npu::utils::toFP32(reference);
const auto outputBuffer = outputFP32.data<const float>();
const auto referenceBuffer = referenceFP32.data<const float>();
const auto size = referenceFP32.get_size();
double numr = 0.0, denA = 0.0, denB = 0.0;
for (size_t i = 0; i < size; ++i) {
numr += outputBuffer[i] * referenceBuffer[i];
denA += outputBuffer[i] * outputBuffer[i];
denB += referenceBuffer[i] * referenceBuffer[i];
}
if (denA == 0 || denB == 0) {
std::cout << "Div by ZERO. Cannot compute CoSim metric" << std::endl;
return false;
}
const auto similarity = numr / (sqrt(denA) * sqrt(denB));
const double eps = 0.0000001;
// Some experiments revealed that when applying the CoSim metric to large buffers it could provide
// similarity values that are outside the [-1:1] interval due the big number of operations done on
// floating point value. A small epsilon value was added to extend the interval to [-(1+eps):1+eps]
// to ensure that the above check is not failing.
if (similarity > (1.0 + eps) || similarity < -(1.0 + eps)) {
std::cout << "Invalid result " << similarity << " (valid range [-1 : +1])" << std::endl;
return false;
}
std::cout << "Cosine similarity : " << similarity * 100 << "%" << std::endl;
return similarity > threshold;
}
bool testCoSim(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
if (outputs.size() != references.size()) {
std::cout << "The outputs and references differ in the number of tensors" << std::endl;
return false;
}
// Parse per-layer thresholds
auto thresholdMap = utils::parsePerLayerValues(FLAGS_cosim_threshold, metric_defaults::cosim_threshold);
bool allPassed = true;
for (const auto& [tensorName, output] : outputs) {
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
double layerThreshold = utils::getValueForLayer(thresholdMap, tensorName);
BlobTestMethod blobComparator = [layerThreshold](ov::Tensor outputTensor, ov::Tensor referenceTensor) {
return compareCoSim(outputTensor, referenceTensor, layerThreshold);
};
if (!test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator)) {
allPassed = false;
}
}
return allPassed;
}
//
// Relative Root Mean Squared Error mode
// (using 'rrmse_loss_threshold' flag, with expected value in range [0.0 -> infinity))
// e.g. '--mode rrmse --rrmse_loss_threshold 0.1'
// e.g. '--mode rrmse --rrmse_loss_threshold "logits:0.1;pred_boxes:0.2"'
//
bool computeRRMSE(const ov::Tensor& output, const ov::Tensor& reference, double threshold) {
if (output.get_shape() != reference.get_shape()) {
std::cout << "Output and reference tensors have different shapes" << std::endl;
return false;
}
const ov::Tensor outputFP32 = npu::utils::toFP32(output);
const ov::Tensor referenceFP32 = npu::utils::toFP32(reference);
const auto outputBuffer = outputFP32.data<const float>();
const auto referenceBuffer = referenceFP32.data<const float>();
const auto size = referenceFP32.get_size();
double error = 0, sum = 0, diff;
for (size_t i = 0; i < size; ++i) {
diff = (outputBuffer[i] - referenceBuffer[i]);
sum += (outputBuffer[i] * outputBuffer[i]);
error += (diff * diff);
}
if (sum == 0) {
if (error <= std::numeric_limits<double>::epsilon()) {
std::cout << "The results perfectly match (error = 0). RRMSE loss could not be computed" << std::endl;
return true;
}
std::cout << "Div by ZERO (Actual is the Zero Tensor). Cannot compute RRMSE loss" << std::endl;
return false;
}
double rrmseLoss = sqrt(error / sum);
std::cout << "RRMSE loss : " << std::fixed << std::setprecision(4) << rrmseLoss
<< " RRMSE threshold : " << std::defaultfloat << threshold << std::endl;
return rrmseLoss <= threshold;
}
bool testRRMSE(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
if (outputs.size() != references.size()) {
std::cout << "Actual and reference has different number of output blobs" << std::endl;
return false;
}
// Parse per-layer thresholds
auto thresholdMap = utils::parsePerLayerValues(FLAGS_rrmse_loss_threshold, metric_defaults::rrmse_loss_threshold);
bool allPassed = true;
for (const auto& [tensorName, output] : outputs) {
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
double layerThreshold = utils::getValueForLayer(thresholdMap, tensorName);
BlobTestMethod blobComparator = [layerThreshold](ov::Tensor outputTensor, ov::Tensor referenceTensor) {
return computeRRMSE(outputTensor, referenceTensor, layerThreshold);
};
if (!test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator)) {
allPassed = false;
}
}
return allPassed;
}
//
// Normalized Mean Squared Error mode
// (using 'nrmse_loss_threshold' flag, with expected value in range [0.0 -> infinity))
// e.g. '--mode nrmse --nrmse_loss_threshold 0.01'
// e.g. '--mode nrmse --nrmse_loss_threshold "logits:0.03;pred_boxes:0.05"'
//
// Optional per-output prefill slicing for LLM KV cache / hidden state outputs:
// --nrmse_prefill_seq_len_axis "<layer>:<axis>;..."
// --nrmse_prefill_seq_len_size "<layer>:<N>;..."
// Keeps only the last N elements along the specified axis before computing NRMSE.
//
// Return a new contiguous tensor containing the last `len` elements of `src` along `axis`.
// The element type and all other dimensions are preserved.
static ov::Tensor sliceLastNAlongAxis(const ov::Tensor& src, size_t axis, size_t len) {
const auto& shape = src.get_shape();
OPENVINO_ASSERT(axis < shape.size(),
"nrmse_prefill_seq_len_axis ", axis,
" is out of range for tensor of rank ", shape.size());
OPENVINO_ASSERT(len > 0 && len <= shape[axis],
"nrmse_prefill_seq_len_size ", len,
" is out of range for axis ", axis, " of size ", shape[axis]);
if (len == shape[axis]) {
return src;
}
ov::Shape newShape = shape;
newShape[axis] = len;
ov::Tensor dst(src.get_element_type(), newShape);
size_t outer = 1;
for (size_t i = 0; i < axis; ++i) {
outer *= shape[i];
}
const size_t mid = shape[axis];
size_t inner = 1;
for (size_t i = axis + 1; i < shape.size(); ++i) {
inner *= shape[i];
}
const size_t elemSize = src.get_element_type().size();
const size_t innerBytes = inner * elemSize;
const size_t srcStart = mid - len;
const auto* srcData = static_cast<const uint8_t*>(src.data());
auto* dstData = static_cast<uint8_t*>(dst.data());
for (size_t o = 0; o < outer; ++o) {
const uint8_t* srcRow = srcData + (o * mid + srcStart) * innerBytes;
uint8_t* dstRow = dstData + (o * len) * innerBytes;
std::memcpy(dstRow, srcRow, len * innerBytes);
}
return dst;
}
bool computeNRMSE(const ov::Tensor& output, const ov::Tensor& reference, double threshold) {
if (output.get_shape() != reference.get_shape()) {
std::cout << "Output and reference tensors have different shapes" << std::endl;
return false;
}
const auto size = reference.get_size();
if (size == 0) {
std::cout << "Empty output and reference tensors, NRMSE loss set to 0" << std::endl;
return true;
}
const ov::Tensor outputFP32 = npu::utils::toFP32(output);
const ov::Tensor referenceFP32 = npu::utils::toFP32(reference);
const auto outputBuffer = outputFP32.data<const float>();
const auto referenceBuffer = referenceFP32.data<const float>();
double error = 0;
float maxOutput = 0, maxReference = 0, minOutput = 0, minReference = 0;
for (size_t i = 0; i < size; ++i) {
const auto diff = outputBuffer[i] - referenceBuffer[i];
error += diff * diff;
maxOutput = std::max(outputBuffer[i], maxOutput);
maxReference = std::max(referenceBuffer[i], maxReference);
minOutput = std::min(outputBuffer[i], minOutput);
minReference = std::min(referenceBuffer[i], minReference);
}
double nrmseLoss =
sqrt(error / size) / std::max(0.001f, std::max(maxOutput - minOutput, maxReference - minReference));
std::cout << "NRMSE loss : " << std::fixed << std::setprecision(4) << nrmseLoss
<< " NRMSE threshold : " << std::defaultfloat << threshold << std::endl;
return nrmseLoss <= threshold;
}
//
// Mean Average Precision mode
// (using 'overlap_threshold' for IoU matching and 'map_threshold' for validation)
// e.g. '--mode map --overlap_threshold 0.5 --map_threshold 0.5'
//
// Full implementation based on Python reference from accuracy_checker/metrics/detection.py
//
bool computeMAP(const std::map<std::string, ov::Tensor>& outputs, const std::map<std::string, ov::Tensor>& references) {
auto confMap = utils::parsePerLayerValues(FLAGS_confidence_threshold, metric_defaults::confidence_threshold);
auto overlapMap = utils::parsePerLayerValues(FLAGS_overlap_threshold, metric_defaults::overlap_threshold);
double confThresh = utils::getValueForLayer(confMap, "*");
double overlapThresh = utils::getValueForLayer(overlapMap, "*");
std::vector<utils::Detection> predictions = utils::parseDetectionsFromOutputs(outputs, static_cast<float>(confThresh));
std::vector<utils::Detection> ground_truth = utils::parseDetectionsFromOutputs(references, static_cast<float>(confThresh));
if (predictions.empty()) {
std::cout << "No predictions found in output tensors" << std::endl;
return false;
}
if (ground_truth.empty()) {
std::cout << "No ground truth detections found in reference tensors" << std::endl;
return false;
}
// Find all unique class IDs
std::set<int> class_ids;
for (const auto& det : predictions) {
class_ids.insert(det.class_id);
}
for (const auto& det : ground_truth) {
class_ids.insert(det.class_id);
}
std::cout << "Computing mAP for " << class_ids.size() << " classes" << std::endl;
// Calculate AP for each class
std::vector<double> average_precisions;
std::map<int, double> per_class_ap;
for (int class_id : class_ids) {
// Match detections for this class
utils::MatchResult match_result = utils::matchDetectionsForClass(predictions,
ground_truth,
class_id,
static_cast<float>(overlapThresh),
true);
if (match_result.confidences.empty()) {
std::cout << " Class " << class_id << ": No predictions" << std::endl;
per_class_ap[class_id] = 0.0;
continue;
}
if (match_result.num_ground_truth == 0) {
std::cout << " Class " << class_id << ": No ground truth" << std::endl;
per_class_ap[class_id] = 0.0;
continue;
}
// Compute cumulative TP and FP
std::vector<float> cum_tp(match_result.tp.size());
std::vector<float> cum_fp(match_result.fp.size());
cum_tp[0] = static_cast<float>(match_result.tp[0]);
cum_fp[0] = static_cast<float>(match_result.fp[0]);
for (size_t i = 1; i < match_result.tp.size(); ++i) {
cum_tp[i] = cum_tp[i - 1] + match_result.tp[i];
cum_fp[i] = cum_fp[i - 1] + match_result.fp[i];
}
// Calculate precision and recall
std::vector<float> precisions;
std::vector<float> recalls;
for (size_t i = 0; i < match_result.tp.size(); ++i) {
float denom = cum_tp[i] + cum_fp[i];
float precision = denom > 0 ? cum_tp[i] / denom : 0.0f;
float recall = cum_tp[i] / static_cast<float>(match_result.num_ground_truth);
precisions.push_back(precision);
recalls.push_back(recall);
}
// Calculate AP for this class
double ap = utils::calculateAveragePrecision(precisions, recalls);
average_precisions.push_back(ap);
per_class_ap[class_id] = ap;
std::cout << " Class " << class_id << ": AP = " << std::fixed << std::setprecision(4)
<< (ap * 100.0) << "% "
<< "(P: " << precisions.back() << ", R: " << recalls.back()
<< ", TP: " << cum_tp.back() << ", FP: " << cum_fp.back()
<< ", GT: " << match_result.num_ground_truth << ")" << std::endl;
}
// Calculate mean AP across all classes
double mean_ap = 0.0;
if (!average_precisions.empty()) {
for (double ap : average_precisions) {
mean_ap += ap;
}
mean_ap /= average_precisions.size();
}
// Parse map_threshold
auto mapThreshMap = utils::parsePerLayerValues(FLAGS_map_threshold, metric_defaults::map_threshold);
double mapThreshold = utils::getValueForLayer(mapThreshMap, "*");
std::cout << "\n=== Mean Average Precision (mAP) ===" << std::endl;
std::cout << " mAP@" << overlapThresh << " = " << std::fixed << std::setprecision(4)
<< (mean_ap * 100.0) << "%" << std::defaultfloat << std::endl;
std::cout << " Number of classes: " << class_ids.size() << std::endl;
std::cout << " mAP threshold: " << (mapThreshold * 100.0) << "%" << std::endl;
return mean_ap >= mapThreshold;
}
bool testMAP(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
if (outputs.size() != references.size()) {
std::cout << "Warning: Actual and reference have different number of output blobs ("
<< outputs.size() << " vs " << references.size() << ")" << std::endl;
}
// Compute mAP from detection model outputs.
// Supports: DETR-style (pred_boxes + logits), YOLOv10-style (single [N,6] tensor)
std::cout << "Computing mAP for detection model" << std::endl;
std::cout << "Output layers:" << std::endl;
for (const auto& [tensorName, tensor] : outputs) {
std::cout << " - " << tensorName << " : " << tensor.get_shape() << std::endl;
}
return computeMAP(outputs, references);
}
std::vector<float> softmax(std::vector<float>& tensor) {
std::vector<double> probabilities(tensor.size());
std::vector<float> results(tensor.size());
// Find the maximum value for numerical stability
float max_value = *std::max_element(tensor.begin(), tensor.end());
// Compute the exponentials of the tensor after subtracting max_value for numerical stability
double sum_exp = 0.0;
for (size_t i = 0; i < tensor.size(); ++i) {
probabilities[i] = exp(tensor[i] - max_value); // exp(tensor_value - max_value) for stability
sum_exp += probabilities[i];
}
// Protect against division by zero
if (sum_exp == 0.0) {
sum_exp = std::numeric_limits<double>::epsilon();
}
// Normalize the probabilities by dividing by the sum of exponentials
for (size_t i = 0; i < tensor.size(); ++i) {
probabilities[i] /= sum_exp;
}
std::transform(probabilities.begin(), probabilities.end(), results.begin(),
[](double value) { return static_cast<float>(value); });
return results;
}
bool testNRMSE(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
if (outputs.size() != references.size()) {
std::cout << "Actual and reference has different number of output blobs" << std::endl;
return false;
}
// Parse per-layer thresholds
auto thresholdMap = utils::parsePerLayerValues(FLAGS_nrmse_loss_threshold, metric_defaults::nrmse_loss_threshold);
// Parse optional per-layer prefill seq-len axis/size maps used to slice LLM
// KV-cache / hidden-state outputs to the last N positions along the sequence axis.
// Only entries that appear in BOTH maps are honored; otherwise the full tensor is compared.
auto seqLenAxisMap = utils::parsePerLayerValues(FLAGS_nrmse_prefill_seq_len_axis, 0.0);
auto seqLenSizeMap = utils::parsePerLayerValues(FLAGS_nrmse_prefill_seq_len_size, 0.0);
bool allPassed = true;
for (auto& [tensorName, output] : outputs) {
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
bool applySoftMax = FLAGS_apply_soft_max;
double layerThreshold = utils::getValueForLayer(thresholdMap, tensorName);
// Optional prefill slicing: applied only when both axis and size are explicitly
// specified for this layer. When only one of the two is given, the full tensor
// is compared and a warning is emitted.
ov::Tensor outputForCompare = output;
ov::Tensor referenceForCompare = referencesIterator->second;
const bool hasAxis = seqLenAxisMap.find(tensorName) != seqLenAxisMap.end();
const bool hasSize = seqLenSizeMap.find(tensorName) != seqLenSizeMap.end();
if (hasAxis && hasSize) {
const size_t axis = static_cast<size_t>(seqLenAxisMap.at(tensorName));
const size_t keep = static_cast<size_t>(seqLenSizeMap.at(tensorName));
std::cout << "Slicing NRMSE input '" << tensorName << "' to last " << keep
<< " element(s) along axis " << axis << std::endl;
outputForCompare = sliceLastNAlongAxis(outputForCompare, axis, keep);
referenceForCompare = sliceLastNAlongAxis(referenceForCompare, axis, keep);
} else if (hasAxis != hasSize) {
std::cout << "Warning: only one of --nrmse_prefill_seq_len_axis / "
"--nrmse_prefill_seq_len_size is set for layer '"
<< tensorName << "'; comparing full tensor." << std::endl;
}
BlobTestMethod blobComparator = [applySoftMax, layerThreshold](ov::Tensor outputTensor, ov::Tensor referenceTensor) {
if (applySoftMax) {
std::vector<float> actOutput;
std::vector<float> refOutput;
std::copy_n((npu::utils::toFP32(outputTensor)).data<const float>(),
outputTensor.get_size(),
std::back_insert_iterator(actOutput));
std::copy_n((npu::utils::toFP32(referenceTensor)).data<const float>(),
referenceTensor.get_size(),
std::back_insert_iterator(refOutput));
const auto actSoftMax = softmax(actOutput);
const auto refSoftMax = softmax(refOutput);
std::copy_n(actSoftMax.begin(), outputTensor.get_size(), outputTensor.data<float>());
// Why reference data is not updated?
std::copy_n(refSoftMax.begin(),
referenceTensor.get_size(),
const_cast<float*>(referenceTensor.data<float>()));
}
return computeNRMSE(outputTensor, referenceTensor, layerThreshold);
};
if (!test_blobs_in_batch(tensorName,
splitBatchedTensor(outputForCompare, tensorName, outputLayouts),
splitBatchedTensor(referenceForCompare, tensorName, outputLayouts),
blobComparator)) {
allPassed = false;
}
}
return allPassed;
}
//
// L2Norm mode
// using l2norm_threshold flag for validation
// e.g. '--mode l2norm --l2norm_threshold <value>'
// Direction of metric’s growth is lower-better. If the inputs are identical, the L2NORM is zero.
//
bool computeL2Norm(const ov::Tensor& output, const ov::Tensor& reference, double threshold,
const std::optional<std::pair<double, double>>& dequant) {
if (output.get_size() != reference.get_size()) {
std::cout << "Output and reference tensors have different sizes" << std::endl;
return false;
}
const ov::Tensor outputFP32 = npu::utils::toFP32(output);
const ov::Tensor referenceFP32 = npu::utils::toFP32(reference);
const auto size = outputFP32.get_size();
const auto* referenceData = referenceFP32.data<const float>();
// Optionally dequantize the inference output before comparing against the (untouched) reference:
// dequantized = (quantized - zero_point) * scale. The reference tensor is never modified.
std::vector<float> dequantizedOutput;
const float* outputData = outputFP32.data<const float>();
if (dequant.has_value()) {
const double scale = dequant->first;
const double zeroPoint = dequant->second;
dequantizedOutput.resize(size);
for (size_t i = 0; i < size; ++i) {
dequantizedOutput[i] = static_cast<float>((static_cast<double>(outputData[i]) - zeroPoint) * scale);
}
outputData = dequantizedOutput.data();
}
double sumSquares = 0.0;
for (size_t i = 0; i < size; ++i) {
const double diff = static_cast<double>(outputData[i]) - static_cast<double>(referenceData[i]);
sumSquares += diff * diff;
}
const double l2norm = std::sqrt(sumSquares);
std::cout << "L2Norm : " << std::fixed << std::setprecision(4) << l2norm
<< " L2Norm threshold : " << std::defaultfloat << threshold << std::endl;
return l2norm <= threshold;
}
bool testL2Norm(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
if (outputs.size() != references.size()) {
std::cout << "Actual and reference has different number of output blobs" << std::endl;
return false;
}
// Parse per-layer thresholds
auto thresholdMap = utils::parsePerLayerValues(FLAGS_l2norm_threshold, metric_defaults::l2norm_threshold);
// Parse optional per-layer dequantization scale/zero-point, used to convert quantized integer
// outputs to floating point before the L2Norm comparison. Dequantization is skipped entirely when
// --l2norm_dequant_scale is not set.
const bool dequantEnabled = !FLAGS_l2norm_dequant_scale.empty();
auto scaleMap = utils::parsePerLayerValues(FLAGS_l2norm_dequant_scale, 1.0);
auto zpMap = utils::parsePerLayerValues(FLAGS_l2norm_dequant_zp, metric_defaults::l2norm_dequant_zp);
const bool scaleIsGlobal = utils::isGlobalValue(scaleMap);
const bool zpIsGlobal = utils::isGlobalValue(zpMap);
bool allPassed = true;
for (auto& [tensorName, output] : outputs) {
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
double layerThreshold = utils::getValueForLayer(thresholdMap, tensorName);
std::optional<std::pair<double, double>> dequant;
if (dequantEnabled) {
std::optional<double> scale =
scaleIsGlobal ? std::optional<double>(utils::getValueForLayer(scaleMap, tensorName))
: utils::getExplicitValueForLayer(scaleMap, tensorName);
if (scale.has_value()) {
const double zeroPoint = zpIsGlobal ? utils::getValueForLayer(zpMap, tensorName)
: utils::getExplicitValueForLayer(zpMap, tensorName)
.value_or(metric_defaults::l2norm_dequant_zp);
dequant = std::make_pair(*scale, zeroPoint);
}
}
BlobTestMethod blobComparator = [layerThreshold, dequant](ov::Tensor outputTensor, ov::Tensor referenceTensor) {
return computeL2Norm(outputTensor, referenceTensor, layerThreshold, dequant);
};
if (!test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator)) {
allPassed = false;
}
}
return allPassed;
}
//
// PSNR mode
// using psnr_reference and psnr_tolerance flags for validation
// e.g. '--mode psnr --psnr_reference <value> --psnr_tolerance <value>'
// Direction of metric’s growth is higher-better. If the images are identical, the PSNR is infinite.
//
bool testPSNR(const TensorMap& outputs, const TensorMap& references, const int dstHeight, const int dstWidth) {
OPENVINO_ASSERT(outputs.size() == references.size(),
"Mismatch between the number of model outputs and the number of references");
// Parse per-layer reference values and tolerances
auto referenceMap = utils::parsePerLayerValues(FLAGS_psnr_reference, metric_defaults::psnr_reference);
auto toleranceMap = utils::parsePerLayerValues(FLAGS_psnr_tolerance, metric_defaults::psnr_tolerance);
double psnrReference = utils::getValueForLayer(referenceMap, "*");
double psnrTolerance = utils::getValueForLayer(toleranceMap, "*");
int scaleBorder = FLAGS_scale_border;
bool normalizedImage = FLAGS_normalized_image;
auto refOutput = npu::utils::parseTensorsAsFP32(references);
auto actOutput = npu::utils::parseTensorsAsFP32(outputs);
auto result = utils::runPSNRMetric(actOutput, refOutput, dstHeight, dstWidth, scaleBorder, normalizedImage);
if (psnrReference - result > psnrTolerance) {
std::cout << "Absolute difference between actual value " << result << " and reference value "
<< psnrReference << " larger then tolerance " << psnrTolerance << std::endl;
return false;
} else {
std::cout << "PASSED (PSNR: " << result << ", Reference: " << psnrReference << ")" << std::endl;
}
return true;
}
static void printPerformanceCountsAndLatency(size_t numberOfTestCase, const ProfVec& profilingData,
std::chrono::duration<double, std::milli> duration) {
auto durationMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
if (!profilingData.empty()) {
std::cout << "Performance counts for " << numberOfTestCase << "-th infer request:" << std::endl;
printPerformanceCounts(profilingData, std::cout, FLAGS_device, false);
}
std::cout << "Latency: " << std::fixed << std::setprecision(2) << durationMs.count() << " ms" << std::defaultfloat << std::endl;
}
bool compare_mean_IoU(std::vector<std::pair<bool, float>> iou, float semSegThreshold, uint32_t classes) {
float threshold = semSegThreshold * 100;
float ma = 0.0f;
bool stateValue = true;
if (FLAGS_sem_seg_ignore_label != std::numeric_limits<uint32_t>::max()) {
classes--;
}
size_t numberOfLabeledClasses = 0;
for (size_t i = 0; i < classes; i++) {
if (iou[i].first) {
numberOfLabeledClasses++;
if (FLAGS_dataset == "camVid12") {
std::cout << "mean_iou@" << camVid12[i].c_str() << ": " << std::fixed << std::setprecision(2)
<< iou[i].second << "%" << std::defaultfloat << std::endl;
} else {
std::cout << "mean_iou@class" << i << ": " << std::fixed << std::setprecision(2) << iou[i].second << "%"
<< std::defaultfloat << std::endl;
}
if (iou[i].second < threshold) {
std::cout << "Threshold smaller than " << threshold << "%" << std::endl;
stateValue = false;
}
ma += iou[i].second;
} else {
std::cout << "mean_iou@class" << i << ": no pixels labeled." << std::endl;
}
}
if (numberOfLabeledClasses > 0) {
std::cout << "mean_iou@:mean " << std::fixed << std::setprecision(2) << (ma / static_cast<float>(numberOfLabeledClasses)) << "%"
<< std::defaultfloat << std::endl;
} else {
std::cout << "WARNING: Number of labeled classes is zero!" << std::endl;
}
return stateValue;
}
// CVS-143420 Allow TEMPLATE plugin to be used instead of CPU to avoid accuracy regressions
#ifdef _WIN32
const char TEMPLATE_LIB[] = "openvino_template_plugin.dll";
#else
const char TEMPLATE_LIB[] = "libopenvino_template_plugin.so";
#endif
void setupOVCore(ov::Core& core) {
if (FLAGS_device == "TEMPLATE") {
core.register_plugin(TEMPLATE_LIB, FLAGS_device);
}
}
void nameIOTensors(std::shared_ptr<ov::Model> model) {
auto inputInfo = model->inputs();
for (std::size_t id = 0ul; id < inputInfo.size(); ++id) {
auto ii = inputInfo[id];
if (ii.get_names().empty()) {
ii.add_names({"input_" + std::to_string(ii.get_index()) + "_" + std::to_string(id)});
}
}
auto outputInfo = model->outputs();
for (std::size_t id = 0ul; id < outputInfo.size(); ++id) {
auto oi = outputInfo[id];
if (oi.get_names().empty()) {
oi.add_names({"output_" + std::to_string(oi.get_index()) + "_" + std::to_string(id)});
}
}
}
std::pair<TensorMap, ProfVec> runInfer(ov::InferRequest& inferRequest, ov::CompiledModel& compiledModel,
const TensorMap& inputs, const std::vector<std::string>& dumpedInputsPaths) {
for (const auto& [tensorName, tensor] : inputs) {
inferRequest.set_tensor(tensorName, tensor);
}
inferRequest.infer();
TensorMap out;
for (const auto& outputInfo : compiledModel.outputs()) {
const std::string layerName = outputInfo.get_any_name();
out.insert({layerName, inferRequest.get_tensor(layerName)});
}
ProfVec profData{};
if (FLAGS_pc) {
profData = inferRequest.get_profiling_info();
}
return std::make_pair(out, profData);
}
bool testSSDDetection(const TensorMap& outputs, const TensorMap& references,
const TensorDescriptorMap& inputDescriptors, const LayoutMap &outputLayouts) {
OPENVINO_ASSERT(outputs.size() == 1 && references.size() == 1);
OPENVINO_ASSERT(!inputDescriptors.empty(), "No input descriptors received");
const TensorDescriptor& inputDescriptor = inputDescriptors.begin()->second;
const auto imgWidth = inputDescriptor.dataShape.at(ov::layout::width_idx(inputDescriptor.layout));
const auto imgHeight = inputDescriptor.dataShape.at(ov::layout::height_idx(inputDescriptor.layout));
// Parse per-layer thresholds
auto confMap = utils::parsePerLayerValues(FLAGS_confidence_threshold, metric_defaults::confidence_threshold);
auto probMap = utils::parsePerLayerValues(FLAGS_prob_tolerance, metric_defaults::prob_tolerance);
auto boxMap = utils::parsePerLayerValues(FLAGS_box_tolerance, metric_defaults::box_tolerance);
const auto& [tensorName, output] = *outputs.begin();
double confThresh = utils::getValueForLayer(confMap, tensorName);
double probTolerance = utils::getValueForLayer(probMap, tensorName);
double boxTolerance = utils::getValueForLayer(boxMap, tensorName);
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
BlobTestMethod blobComparator = [imgWidth, imgHeight, confThresh, probTolerance, boxTolerance](
const ov::Tensor& outputTensor,
const ov::Tensor& referenceTensor) {
auto parsedOutput = utils::parseSSDOutput(outputTensor, imgWidth,
imgHeight, static_cast<float>(confThresh));
auto parsedReference = utils::parseSSDOutput(referenceTensor, imgWidth,
imgHeight, static_cast<float>(confThresh));
return checkBBoxOutputs(parsedOutput,
parsedReference,
imgWidth,
imgHeight,
static_cast<float>(boxTolerance),
static_cast<float>(probTolerance));
};
return test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator);
}
//
// Yolo V2 mode
//
bool testYoloV2(const TensorMap& outputs, const TensorMap& references, const TensorDescriptorMap& inputDescriptors, const LayoutMap &outputLayouts) {
OPENVINO_ASSERT(inputDescriptors.size() == 1, "The YOLO v2 model accepts only a single input");
OPENVINO_ASSERT(outputs.size() == 1, "The YOLO v2 model a single output");
OPENVINO_ASSERT(outputs.size() == references.size(),
"Mismatch between the number of model outputs and the number of references");
const TensorDescriptor& inputDescriptor = inputDescriptors.begin()->second;
const auto imgWidth = inputDescriptor.dataShape.at(ov::layout::width_idx(inputDescriptor.layout));
const auto imgHeight = inputDescriptor.dataShape.at(ov::layout::height_idx(inputDescriptor.layout));
// Parse per-layer thresholds
auto confMap = utils::parsePerLayerValues(FLAGS_confidence_threshold, metric_defaults::confidence_threshold);
auto probMap = utils::parsePerLayerValues(FLAGS_prob_tolerance, metric_defaults::prob_tolerance);
auto boxMap = utils::parsePerLayerValues(FLAGS_box_tolerance, metric_defaults::box_tolerance);
bool isTiny = FLAGS_is_tiny_yolo;
const auto& [tensorName, output] = *outputs.begin();
double confThresh = utils::getValueForLayer(confMap, tensorName);
double probTolerance = utils::getValueForLayer(probMap, tensorName);
double boxTolerance = utils::getValueForLayer(boxMap, tensorName);
auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
BlobTestMethod blobComparator = [imgWidth, imgHeight, confThresh, probTolerance, boxTolerance, isTiny](
const ov::Tensor& outputTensor,
const ov::Tensor& referenceTensor) {
auto parsedOutput = utils::parseYoloOutput(npu::utils::toFP32(outputTensor),
imgWidth,
imgHeight,
static_cast<float>(confThresh),
isTiny);
auto parsedReference = utils::parseYoloOutput(npu::utils::toFP32(referenceTensor),
imgWidth,
imgHeight,
static_cast<float>(confThresh),
isTiny);
return checkBBoxOutputs(parsedOutput,
parsedReference,
imgWidth,
imgHeight,
static_cast<float>(boxTolerance),
static_cast<float>(probTolerance));
};
return test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator);
}
//
// Yolo V3 mode
//
bool testYoloV3(const TensorMap& outputs, const TensorMap& references, const TensorDescriptorMap& inputDescriptors,
const LayoutMap& outputLayouts) {
OPENVINO_ASSERT(inputDescriptors.size() == 1, "The YOLO v3 model accepts only a single input");
OPENVINO_ASSERT(outputs.size() == 3, "The YOLO v3 model has three outputs");
OPENVINO_ASSERT(outputs.size() == references.size(),
"Mismatch between the number of model outputs and the number of references");
const TensorDescriptor& inputDescriptor = inputDescriptors.begin()->second;
const auto imgWidth = inputDescriptor.dataShape.at(ov::layout::width_idx(inputDescriptor.layout));
const auto imgHeight = inputDescriptor.dataShape.at(ov::layout::height_idx(inputDescriptor.layout));
// Parse per-layer thresholds (use global values for Yolo V3 as it processes all outputs together)
auto confMap = utils::parsePerLayerValues(FLAGS_confidence_threshold, metric_defaults::confidence_threshold);
auto probMap = utils::parsePerLayerValues(FLAGS_prob_tolerance, metric_defaults::prob_tolerance);
auto boxMap = utils::parsePerLayerValues(FLAGS_box_tolerance, metric_defaults::box_tolerance);
double confThresh = utils::getValueForLayer(confMap, "*");
double probTolerance = utils::getValueForLayer(probMap, "*");
double boxTolerance = utils::getValueForLayer(boxMap, "*");
int classes = FLAGS_classes;
int coords = FLAGS_coords;
int num = FLAGS_num;
std::vector<float> anchors = {10.0, 13.0, 16.0, 30.0, 33.0, 23.0, 30.0, 61.0, 62.0,
45.0, 59.0, 119.0, 116.0, 90.0, 156.0, 198.0, 373.0, 326.0};
auto parsedOutput = utils::parseYoloV3Output(outputs, imgWidth, imgHeight, classes, coords, num, anchors,
static_cast<float>(confThresh), transformLayoutDescriptionToAnyLayoutsMap(outputLayouts));
auto parsedReference = utils::parseYoloV3Output(references, imgWidth, imgHeight, classes, coords, num, anchors,
static_cast<float>(confThresh), transformLayoutDescriptionToAnyLayoutsMap(outputLayouts));
bool result = checkBBoxOutputs(parsedOutput, parsedReference, imgWidth, imgHeight, static_cast<float>(boxTolerance),
static_cast<float>(probTolerance));
return result;
}
//
// Yolo V4 mode
// Ref link: https://docs.openvino.ai/latest/omz_models_model_yolo_v4_tiny_tf.html
//
bool testYoloV4(const TensorMap& outputs, const TensorMap& references, const TensorDescriptorMap& inputDescriptors,
const LayoutMap& outputLayouts) {
OPENVINO_ASSERT(inputDescriptors.size() == 1, "The YOLO v4 model accepts only a single input");
OPENVINO_ASSERT(outputs.size() == 2, "The YOLO v4 model has two outputs");
OPENVINO_ASSERT(outputs.size() == references.size(),
"Mismatch between the number of model outputs and the number of references");
const TensorDescriptor& inputDescriptor = inputDescriptors.begin()->second;
const auto imgWidth = inputDescriptor.dataShape.at(ov::layout::width_idx(inputDescriptor.layout));
const auto imgHeight = inputDescriptor.dataShape.at(ov::layout::height_idx(inputDescriptor.layout));
// Parse per-layer thresholds (use global values for Yolo V4 as it processes all outputs together)
auto confMap = utils::parsePerLayerValues(FLAGS_confidence_threshold, metric_defaults::confidence_threshold);
auto probMap = utils::parsePerLayerValues(FLAGS_prob_tolerance, metric_defaults::prob_tolerance);
auto boxMap = utils::parsePerLayerValues(FLAGS_box_tolerance, metric_defaults::box_tolerance);
double confThresh = utils::getValueForLayer(confMap, "*");
double probTolerance = utils::getValueForLayer(probMap, "*");
double boxTolerance = utils::getValueForLayer(boxMap, "*");
int classes = FLAGS_classes;
int coords = FLAGS_coords;
int num = FLAGS_num;
std::vector<float> anchors = {10.0, 14.0, 23.0, 27.0, 37.0, 58.0, 81.0, 82.0, 135.0, 169.0, 344.0, 319.0};
std::vector<std::vector<float>> anchor_mask{{3, 4, 5}, {1, 2, 3}};
std::vector<float> masked_anchors{};
for (auto& it : anchor_mask) {
int index = 0;
for (auto& anchorIndex : it) {
if (index >= num)
break;
index++;
masked_anchors.push_back(anchors[static_cast<size_t>(2 * anchorIndex)]);
masked_anchors.push_back(anchors[static_cast<size_t>(2 * anchorIndex + 1)]);
}
}
auto refOutput = utils::parseYoloV4Output(references,
imgWidth,
imgHeight,
classes,
coords,
num,
masked_anchors,
static_cast<float>(confThresh),
transformLayoutDescriptionToAnyLayoutsMap(outputLayouts));
auto actOutput = utils::parseYoloV4Output(outputs,
imgWidth,
imgHeight,
classes,
coords,
num,
masked_anchors,
static_cast<float>(confThresh),
transformLayoutDescriptionToAnyLayoutsMap(outputLayouts));
bool result = checkBBoxOutputs(actOutput,
refOutput,
imgWidth,
imgHeight,
static_cast<float>(boxTolerance),
static_cast<float>(probTolerance));
return result;
}
//
// MeanIoU mode
// Using sem_seg_classes, sem_seg_threshold flags and optionally sem_seg_ignore_label and dataset flags for validation
// e.g. '--mode mean_iou --sem_seg_classes 12 --sem_seg_threshold 0.98 --sem_seg_ignore_label 11 --dataset camVid12'
//
bool testMeanIoU(const TensorMap& outputs, const TensorMap& references, const LayoutMap& outputLayouts) {
OPENVINO_ASSERT(outputs.size() == 1, "The metric accepts only a single output");
OPENVINO_ASSERT(outputs.size() == references.size(),
"Mismatch between the number of model outputs and the number of references");
OPENVINO_ASSERT(outputs.size() == outputLayouts.size(),
"Mismatch between the number of model outputs and their corresponding layout values");
bool skipArgMax = FLAGS_skip_arg_max;
unsigned int classes = FLAGS_sem_seg_classes;
// Parse sem_seg_threshold (can be per-layer or global)
auto thresholdMap = utils::parsePerLayerValues(FLAGS_sem_seg_threshold, metric_defaults::sem_seg_threshold);
const auto& [tensorName, output] = *outputs.begin();
float semSegThreshold = static_cast<float>(utils::getValueForLayer(thresholdMap, tensorName));
std::vector<std::pair<bool, float>> iou(classes, {false, 0.0f});
const auto referencesIterator = references.find(tensorName);
OPENVINO_ASSERT(referencesIterator != references.end());
const auto outputLayoutIterator = outputLayouts.find(tensorName);
OPENVINO_ASSERT(outputLayoutIterator != outputLayouts.end());
BlobTestMethod blobComparator = [skipArgMax, outputLayoutIterator, classes, semSegThreshold, &iou](
const ov::Tensor& outputTensor,
const ov::Tensor& referenceTensor) {
std::vector<uint8_t> parsedReferences, parsedOutputs;
if (skipArgMax) {
const ov::Tensor referenceU8 = npu::utils::toPrecision(referenceTensor, ov::element::u8);
const ov::Tensor outputU8 = npu::utils::toPrecision(outputTensor, ov::element::u8);
const size_t C =
referenceU8.get_shape()[ov::layout::channels_idx(outputLayoutIterator->second.getAnyLayout())];
const size_t H =
referenceU8.get_shape()[ov::layout::height_idx(outputLayoutIterator->second.getAnyLayout())];
const size_t W =
referenceU8.get_shape()[ov::layout::width_idx(outputLayoutIterator->second.getAnyLayout())];
std::copy_n(referenceU8.data<uint8_t>(), C * H * W, std::back_insert_iterator(parsedReferences));
std::copy_n(outputU8.data<uint8_t>(), C * H * W, std::back_insert_iterator(parsedOutputs));
} else {
utils::argMax_channels(referenceTensor, parsedReferences, outputLayoutIterator->second.getAnyLayout());
utils::argMax_channels(outputTensor, parsedOutputs, outputLayoutIterator->second.getAnyLayout());
}
if (parsedReferences.size() != parsedOutputs.size()) {
std::cout << "Reference size and output size are different" << std::endl;
return false;
}
iou = utils::mean_IoU(parsedOutputs, parsedReferences, classes, FLAGS_sem_seg_ignore_label);
return compare_mean_IoU(iou, semSegThreshold, classes);
};
return test_blobs_in_batch(tensorName,
splitBatchedTensor(output, tensorName, outputLayouts),
splitBatchedTensor(referencesIterator->second, tensorName, outputLayouts),
blobComparator);
}
// Parses a comma separated list of non-negative dimensions, e.g. "1,3,224,224".
static ov::Shape parseDimensions(const std::string& dimensionsStr) {
ov::Shape dataShape;
std::stringstream ss(dimensionsStr);
std::string dimStr;
while (std::getline(ss, dimStr, ',')) {
const bool isNumber = !dimStr.empty() && std::all_of(dimStr.begin(), dimStr.end(), [](unsigned char ch) {
return std::isdigit(ch) != 0;
});
OPENVINO_ASSERT(isNumber, "Dimension \"", dimStr, "\" of the shape \"", dimensionsStr,
"\" is not a non-negative integer");
try {
dataShape.push_back(std::stoull(dimStr));
} catch (const std::out_of_range&) {
OPENVINO_THROW("Dimension \"", dimStr, "\" of the shape \"", dimensionsStr, "\" is out of range");
}
}
OPENVINO_ASSERT(!dataShape.empty(), "Can't parse \"", dimensionsStr, "\" as a shape");
return dataShape;
}
// Data shapes by tensor name, as returned by ov::Output::get_any_name().
using DataShapes = std::map<std::string, ov::Shape>;
// Parses --data_shape. Accepted formats:
// - "[1,3,224,224]" or "1,3,224,224": a single shape used for every input;
// - "input1[1,3,224,224],input2[1,4]": one shape per input.
static DataShapes parseDataShapes(std::string dataShapeStr,
const std::vector<ov::Output<const ov::Node>>& inputsInfo) {
dataShapeStr.erase(std::remove_if(dataShapeStr.begin(), dataShapeStr.end(),
[](unsigned char ch) {
return std::isspace(ch) != 0;
}),
dataShapeStr.end());
DataShapes dataShapes;
if (dataShapeStr.empty()) {
return dataShapes;
}
// The shared parser expects bracketed values, while --data_shape also accepts a bare "1,3,224,224".
const std::string bracketed =
dataShapeStr.find('[') == std::string::npos ? "[" + dataShapeStr + "]" : dataShapeStr;
std::map<std::string, std::vector<std::string>> shapesPerInput;
try {
shapesPerInput = parseInputParameters(bracketed, inputsInfo);
} catch (const std::exception& ex) {
OPENVINO_THROW("Can't parse --data_shape \"", dataShapeStr, "\": ", ex.what());
}
for (const auto& entry : shapesPerInput) {
OPENVINO_ASSERT(entry.second.size() == 1, "--data_shape contains more than one shape for input \"",
entry.first, "\"");
dataShapes.emplace(entry.first, parseDimensions(entry.second.front()));
}
return dataShapes;
}
static ov::Shape getDataShape(const DataShapes& dataShapes, const ov::Output<const ov::Node>& inputInfo) {
const auto it = dataShapes.find(inputInfo.get_any_name());
OPENVINO_ASSERT(it != dataShapes.end(), "--data_shape has no shape for the dynamic input \"",
inputInfo.get_any_name(), "\"");
return it->second;
}
std::string getRefBlobFilePath(const std::string& blobNamePrefix, const std::vector<std::string>& refFiles,
size_t numberOfTestCase, size_t outputInd) {
std::string blobFileFullPath;
if (!refFiles.empty() && !FLAGS_ref_dir.empty()) {
// Case 1: Reference files & directory are provided (relative path)
std::filesystem::path refDirPath(FLAGS_ref_dir);
std::filesystem::path refFilePath(refFiles[outputInd]);
blobFileFullPath = (refDirPath / refFilePath).string();
} else if (!refFiles.empty()) {
// Case 2: Reference files provided only (absolute path)
blobFileFullPath = refFiles[outputInd];
} else {
// Case 3: Reference directory provided only
std::ostringstream ostr;
ostr << blobNamePrefix << "_ref_out_" << outputInd << "_case_" << numberOfTestCase << ".blob";
const auto blobFileName = ostr.str();
std::filesystem::path fullPath = FLAGS_ref_dir;
fullPath /= blobFileName;
blobFileFullPath = fullPath.string();
}
return blobFileFullPath;
}
static int runSingleImageTest() {
std::cout << "Run single image test" << std::endl;
try {
// Flow of Single Image Test
// 1. Parse input and output precisions (if given)
// 2. Parse input and output layouts (if given)
// 3. Parse input files (if given)
// 4. Parse input files as binaries (if given) according to precision
// 5. Setup OpenVINO Core
// 6. Load network if possible, else directly load as binary
// 7. (For loadable networks) Configure pre-/post-processing (precision and layout)
// 8. (For loadable networks) Perform reshape (reshape will only be done if either
// shape or override_model_batch_size is specified)
// 9. (For loadable networks) Compile model
// 10. Store compile model (if given)
// 11. Run inference / tests
const std::unordered_set<std::string> allowedPrecision = {"U8", "I32", "I64", "FP16", "FP32",
"U16", "I16", "U4", "I4", "U2", "BF8", "F8E5M2", "HF8", "F8E4M3"};
const std::map<std::string, std::string> precisionNameAliases = {{"BF8", "F8E5M2"}, {"HF8", "F8E4M3"}};
if (!FLAGS_ip.empty()) {
// input precision: U8, U16, I16, I32, I64, FP16, FP32, U4, I4, U2, BF8(F8E5M2), HF8(F8E4M3)
std::transform(FLAGS_ip.begin(), FLAGS_ip.end(), FLAGS_ip.begin(), ::toupper);
for (const auto& [alias, real] : precisionNameAliases) {
if (FLAGS_ip == alias) {
FLAGS_ip = real;
std::cout << "Input precision alias " << alias << " is used, converted to " << real << std::endl;
break;
}
}
if (allowedPrecision.count(FLAGS_ip) == 0)
throw std::logic_error("Parameter -ip " + FLAGS_ip + " is not supported");
}
if (!FLAGS_op.empty()) {
// output precision: U8, U16, I16, I32, I64, FP16, FP32, U4, I4, U2, BF8(F8E5M2), HF8(F8E4M3)
std::transform(FLAGS_op.begin(), FLAGS_op.end(), FLAGS_op.begin(), ::toupper);
for (const auto& [alias, real] : precisionNameAliases) {
if (FLAGS_op == alias) {
FLAGS_op = real;
std::cout << "Output precision alias " << alias << " is used, converted to " << real << std::endl;
break;
}
}
if (allowedPrecision.count(FLAGS_op) == 0)
throw std::logic_error("Parameter -op " + FLAGS_op + " is not supported");
}
std::map<RegexPtr, ov::Layout> inUserLayouts = parseLayoutRegex(FLAGS_il);
std::map<RegexPtr, ov::Layout> outUserLayouts = parseLayoutRegex(FLAGS_ol);
std::map<RegexPtr, ov::Layout> inModelLayouts = parseLayoutRegex(FLAGS_iml);
std::map<RegexPtr, ov::Layout> outModelLayouts = parseLayoutRegex(FLAGS_oml);
if (FLAGS_network.empty()) {
std::cout << "Not enough parameters. (Network not specified). Check help." << std::endl;
return EXIT_FAILURE;
}
ov::Core core;
setupOVCore(core);
ov::CompiledModel compiledModel;
if (hasLoadableExt(FLAGS_network)) {
std::cout << "Load network " << FLAGS_network << std::endl;
auto model = core.read_model(FLAGS_network);
nameIOTensors(model);
ov::preprocess::PrePostProcessor ppp(model);
const ov::OutputVector inputInfo = model->inputs();
// Input precision
if (!FLAGS_ip.empty()) {
ov::element::Type prc_in = ov::element::Type(FLAGS_ip);
for (size_t i = 0; i < inputInfo.size(); ++i) {
ppp.input(i).tensor().set_element_type(prc_in);
}
}
// Input layout
for (size_t i = 0; i < inputInfo.size(); ++i) {
if (std::optional<ov::Layout> inUserLayout =
getRegexSubstitutionIfExist(inputInfo[i].get_any_name(), inUserLayouts);
inUserLayout.has_value()) {
ov::Layout inLayerModelLayout;
if (std::optional<ov::Layout> inModelLayout =
getRegexSubstitutionIfExist(inputInfo[i].get_any_name(), inModelLayouts);
inModelLayout.has_value()) {
inLayerModelLayout = inModelLayout.value();
} else {
const auto shape = inputInfo[i].get_partial_shape();
inLayerModelLayout = getLayoutByRank(shape.size());
std::cout << "WARNING: Configuring preprocessing. Since --iml option isn't set, input model "
"layout for layer \""
<< inputInfo[i].get_any_name() << "\" is infered from shape: " << shape.to_string()
<< " rank (" << shape.size() << ") as " << inLayerModelLayout.to_string()
<< std::endl;
}
std::cout << "Set layouts for the input: \"" << inputInfo[i].get_any_name() << "\", model "
<< inLayerModelLayout.to_string() << ", user " << inUserLayout.value().to_string()
<< std::endl;
ppp.input(i).model().set_layout(inLayerModelLayout);
ppp.input(i).tensor().set_layout(inUserLayout.value());
}
}
// Input mean and scale if exist
if (!FLAGS_mean_values.empty() || !FLAGS_scale_values.empty()) {
auto means = parseMeanOrScale(FLAGS_mean_values, inputInfo);
auto scales = parseMeanOrScale(FLAGS_scale_values, inputInfo);
for (size_t i = 0; i < inputInfo.size(); ++i) {
if (!means[i].empty()) {
ppp.input(i).preprocess().convert_element_type(ov::element::f32).mean(means[i]);
}
if (!scales[i].empty()) {
ppp.input(i).preprocess().convert_element_type(ov::element::f32).scale(scales[i]);
}
}
}
// Output precision
const auto outputInfo = model->outputs();
if (!FLAGS_op.empty()) {
ov::element::Type prc_out = ov::element::Type(FLAGS_op);
for (size_t i = 0; i < outputInfo.size(); ++i) {
ppp.output(i).tensor().set_element_type(prc_out);
if (prc_out == ov::element::u8 && FLAGS_clamp_u8_outputs) {
ppp.output(i).postprocess().clamp(0.0, 255.0);
}
}
}
// Output layout
for (size_t i = 0; i < outputInfo.size(); ++i) {
if (std::optional<ov::Layout> outUserLayout =
getRegexSubstitutionIfExist(outputInfo[i].get_any_name(), outUserLayouts);
outUserLayout.has_value()) {
ov::Layout outLayerModelLayout;
if (std::optional<ov::Layout> outModelLayout =
getRegexSubstitutionIfExist(outputInfo[i].get_any_name(), outModelLayouts);
outModelLayout.has_value()) {
outLayerModelLayout = outModelLayout.value();
} else {
const auto shape = outputInfo[i].get_partial_shape();
outLayerModelLayout = getLayoutByRank(shape.size());
std::cout << "WARNING: Configuring preprocessing. Since --oml option isn't set, output model "
"layout for layer \""
<< outputInfo[i].get_any_name() << "\" is infered from shape: " << shape.to_string()
<< " rank (" << shape.size() << ") as " << outLayerModelLayout.to_string()
<< std::endl;
}
std::cout << "Set layouts for the output: \"" << outputInfo[i].get_any_name() << "\", model "
<< outLayerModelLayout.to_string() << ", user " << outUserLayout.value().to_string()
<< std::endl;
ppp.output(i).model().set_layout(outLayerModelLayout);
ppp.output(i).tensor().set_layout(outUserLayout.value());
}
}
auto inputsInfo = std::const_pointer_cast<ov::Model>(model)->inputs();
InputsInfo infoMap;
printInputAndOutputsInfoShort(*model);
std::cout << "Performing reshape" << std::endl;
reshape(std::move(inputsInfo), infoMap, model, FLAGS_shape,
FLAGS_override_model_batch_size, FLAGS_device);
std::cout << "Compile model" << std::endl;
model = ppp.build();
printInputAndOutputsInfoShort(*model);
compiledModel = core.compile_model(model, FLAGS_device, buildDeviceConfig());
} else {
std::cout << "Import network " << FLAGS_network << std::endl;
if (!FLAGS_mean_values.empty() || !FLAGS_scale_values.empty()) {
throw std::runtime_error("--mean_values and --scale_values aren't supported for "
"compiled model.\n The values can be set via "
"model_optimizer while generating xml\n");
}
std::ifstream file(FLAGS_network, std::ios_base::in | std::ios_base::binary);
OPENVINO_ASSERT(file.is_open(), "Can't open file ", FLAGS_network, " for read");
compiledModel = core.import_model(file, FLAGS_device, buildDeviceConfig());
}
auto inputInfo = compiledModel.inputs();
// Declare input file variables
std::vector<std::string> inputFilesPerCase;
using FilesPerInput = std::vector<std::string>;
using FilesForModelInputs = std::vector<FilesPerInput>;
std::vector<FilesForModelInputs> inputFilesForOneInfer;
// Parse input files string (matching of node names - if given)
std::string processedFileInputs = parseInputFiles(inputInfo, FLAGS_input);
inputFilesPerCase = splitStringList(processedFileInputs, ';');
for (const auto& images : inputFilesPerCase) {
std::vector<std::string> filesPerModel = splitStringList(images, ',');
FilesForModelInputs entireModelFiles;
entireModelFiles.reserve(filesPerModel.size());
for (auto &&filesPerInput : filesPerModel) {
// from now on each input of a model support multiple image files as content of a batched input
entireModelFiles.push_back(splitStringList(filesPerInput, '|'));
}
inputFilesForOneInfer.push_back(std::move(entireModelFiles));
}
// Declare output file / reference file variables
std::vector<std::string> refFilesPerCase;
using RefFilesPerInput = std::vector<std::string>;
using RefFilesForModelOutputs = std::vector<RefFilesPerInput>;
RefFilesForModelOutputs refFilesForOneInfer;
// Parse reference files
if (!FLAGS_ref_results.empty()) {
refFilesPerCase = splitStringList(FLAGS_ref_results, ';');
// Make sure that the number of test cases (separated by ;) is the same as number of test cases given in
// input files
if (refFilesPerCase.size() != inputFilesPerCase.size()) {
std::cout << "The number of test cases in reference files is not equal to the number of test cases"
<< " given in input files. "
<< " Number of test cases in reference files: " << refFilesPerCase.size()
<< " Number of test cases in input files: " << inputFilesPerCase.size() << std::endl;
return EXIT_FAILURE;
}
for (const auto& refResult : refFilesPerCase) {
std::vector<std::string> refFilesPerModel = splitStringList(refResult, ',');
refFilesForOneInfer.push_back(std::move(refFilesPerModel));
}
}
std::vector<std::string> inputBinPrecisionStrPerCase;
std::vector<std::vector<ov::element::Type>> inputBinPrecisionForOneInfer(inputFilesForOneInfer.size());
if (FLAGS_img_as_bin) {
for (std::size_t i = 0; i < inputFilesForOneInfer.size(); ++i) {
inputBinPrecisionForOneInfer[i] =
std::vector<ov::element::Type>(inputFilesForOneInfer[i].size(), ov::element::dynamic);
}
inputBinPrecisionStrPerCase = splitStringList(FLAGS_img_bin_precision, ';');
std::size_t inferIdx = 0;
for (const auto& precisions : inputBinPrecisionStrPerCase) {
std::vector<std::string> inputBinPrecisionsStrThisInfer = splitStringList(precisions, ',');
std::size_t precisionIdx = 0;
for (const auto& precision : inputBinPrecisionsStrThisInfer) {
std::string precision_str = precision;
std::transform(precision_str.begin(), precision_str.end(), precision_str.begin(), ::toupper);
for (const auto& [alias, real] : precisionNameAliases) {
if (precision_str == alias) {
precision_str = real;
break;
}
}
inputBinPrecisionForOneInfer[inferIdx][precisionIdx] = ov::element::Type(precision_str);
++precisionIdx;
}
++inferIdx;
}
}
// store compiled model, if required
if (!FLAGS_compiled_blob.empty()) {
std::ofstream outputFile{FLAGS_compiled_blob, std::ios::out | std::ios::binary};
if (!outputFile.is_open()) {
std::cerr << "Output file \"" << FLAGS_compiled_blob << "\" can't be opened for writing" << std::endl;
return EXIT_FAILURE;
} else {
compiledModel.export_model(outputFile);
}
}
auto inferRequest = compiledModel.create_infer_request();
std::string netFileName;
{
auto startPos = FLAGS_network.rfind('/');
if (startPos == std::string::npos) {
startPos = FLAGS_network.rfind('\\');
if (startPos == std::string::npos) {
startPos = 0;
}
}
auto endPos = FLAGS_network.rfind('.');
if (endPos == std::string::npos) {
endPos = FLAGS_network.size();
}
OPENVINO_ASSERT(endPos > startPos);
netFileName = cleanName(FLAGS_network.substr(startPos, endPos - startPos));
}
const std::string blobNamePrefix =
FLAGS_blob_name_prefix.empty() ? netFileName : cleanName(FLAGS_blob_name_prefix);
const DataShapes dataShapes = parseDataShapes(FLAGS_data_shape, compiledModel.inputs());
for (size_t numberOfTestCase = 0; numberOfTestCase < inputFilesPerCase.size(); ++numberOfTestCase) {
const auto inputsInfo = compiledModel.inputs();
const auto outputsInfo = compiledModel.outputs();
const FilesForModelInputs &inputFiles = inputFilesForOneInfer[numberOfTestCase];
OPENVINO_ASSERT(inputFiles.size() == inputsInfo.size(), "Number of input files ", inputFiles.size(),
" doesn't match network configuration ", inputsInfo.size());
const RefFilesPerInput &refFiles = refFilesForOneInfer.empty() ? RefFilesPerInput{}
: refFilesForOneInfer[numberOfTestCase];
if (!FLAGS_ref_results.empty()) {
OPENVINO_ASSERT(refFiles.size() == outputsInfo.size(), "Number of reference files ", refFiles.size(),
" doesn't match number of network output (s): ", outputsInfo.size());
}
TensorMap inTensors;
size_t inputInd = 0;
std::vector<std::string> dumpedInputsPaths;
TensorDescriptorMap inputDescriptors; // Several metrics require the input metadata
// Load the input data
for (const auto& inputInfo : inputsInfo) {
const auto& shape = inputInfo.get_partial_shape();
const auto dataShape = shape.is_static() ? shape.get_shape() : getDataShape(dataShapes, inputInfo);
OPENVINO_ASSERT(shape.compatible(ov::PartialShape(dataShape)), "Data shape ", dataShape,
" of the input \"", inputInfo.get_any_name(), "\" is not compatible with ", shape);
const ov::element::Type& precision = inputInfo.get_element_type();
// Determine the input layout
ov::Layout inputLayout;
if (std::optional<ov::Layout> inUserLayout =
getRegexSubstitutionIfExist(inputInfo.get_any_name(), inUserLayouts);
inUserLayout.has_value()) {
inputLayout = inUserLayout.value();
} else if (std::optional<ov::Layout> inModelLayout =
getRegexSubstitutionIfExist(inputInfo.get_any_name(), inModelLayouts);
inModelLayout.has_value()) {
inputLayout = inModelLayout.value();
} else {
inputLayout = getLayoutByRank(shape.size());
std::cout << "WARNING: Loading input data. Since --iml option isn't set, input model layout for "
"layer \""
<< inputInfo.get_any_name() << "\" is infered from shape: " << shape.to_string()
<< " rank (" << shape.size() << ") as " << inputLayout.to_string() << std::endl;
}
inputDescriptors.emplace(inputInfo.get_any_name(), TensorDescriptor{precision, shape,
dataShape, inputLayout});
std::cout << "Load input #" << inputInd << " from " << to_string(inputFiles[inputInd]) << " as " << precision
<< " " << inputLayout.to_string() << " " << shape << std::endl;
const ov::Tensor tensor =
!FLAGS_img_as_bin
? loadInput(precision, dataShape, inputLayout, inputFiles[inputInd], FLAGS_color_format)
: loadInput(precision, dataShape, inputLayout, inputFiles[inputInd], FLAGS_color_format,
inputBinPrecisionForOneInfer[numberOfTestCase][inputInd]);
std::ostringstream ostr;
ostr << blobNamePrefix << "_input_" << inputInd << "_case_" << numberOfTestCase << ".blob";
const auto blobFileName = ostr.str();
std::cout << "Dump input #" << inputInd << "_case_" << numberOfTestCase << " to " << blobFileName
<< std::endl;
dumpTensor(tensor, blobFileName);
++inputInd;
dumpedInputsPaths.push_back(blobFileName);
inTensors.emplace(inputInfo.get_any_name(), std::move(tensor));
}
std::cout << "Run inference on " << FLAGS_device << std::endl;
const auto startTime = Time::now();
auto outInference = runInfer(inferRequest, compiledModel, inTensors, dumpedInputsPaths);
const auto endTime = Time::now();
TensorMap& outputTensors = outInference.first;
printPerformanceCountsAndLatency(numberOfTestCase, outInference.second, endTime - startTime);
if (FLAGS_run_test) {
TensorMap referenceTensors;
size_t outputInd = 0;
LayoutMap outputLayouts; // Several metrics may require this
// Load the reference data
for (const auto& out : compiledModel.outputs()) {
const auto& tensorName = out.get_any_name();
const auto& tensor = outputTensors.at(tensorName);
const ov::element::Type& precision = tensor.get_element_type();
const ov::Shape& shape = tensor.get_shape();
std::string blobFileFullPath =
getRefBlobFilePath(blobNamePrefix, refFiles, numberOfTestCase, outputInd);
std::cout << "Load reference output #" << outputInd << " from " << blobFileFullPath << " as "
<< precision << std::endl;
referenceTensors.emplace(tensorName, loadTensor(precision, shape, blobFileFullPath));
// Determine the output layout
outputLayouts.emplace(
tensorName,
LayoutDescription::create(tensorName, outUserLayouts, outModelLayouts, shape));
++outputInd;
}
outputInd = 0;
// Dump the outputs obtained upon prediction
for (const auto& out : compiledModel.outputs()) {
const auto& tensor = outputTensors.at(out.get_any_name());
std::ostringstream ostr;
ostr << blobNamePrefix << "_kmb_out_" << outputInd << "_case_" << numberOfTestCase << ".blob";
const auto blobFileName = ostr.str();
std::cout << "Dump device output #" << outputInd << "_case_" << numberOfTestCase << " to "
<< blobFileName << std::endl;
dumpTensor(tensor, blobFileName);
++outputInd;
}
// Filter out skipped layers before passing to test methods
TensorMap filteredOutputTensors;
TensorMap filteredReferenceTensors;
LayoutMap filteredOutputLayouts;
std::vector<std::string> skipped_layers = splitStringList(FLAGS_skip_output_layers, ';');
for (const auto& [tensorName, tensor] : outputTensors) {
if (std::find(skipped_layers.begin(), skipped_layers.end(), tensorName) != skipped_layers.end()) {
std::cout << "Skip test for layer: " << tensorName << std::endl;
continue;
}
auto refIt = referenceTensors.find(tensorName);
if (refIt == referenceTensors.end()) {
std::cerr << "Reference tensor not found for output layer: " << tensorName << std::endl;
continue;
}
filteredOutputTensors[tensorName] = tensor;
filteredReferenceTensors[tensorName] = refIt->second;
auto layoutIt = outputLayouts.find(tensorName);
if (layoutIt != outputLayouts.end()) {
filteredOutputLayouts.emplace(tensorName, layoutIt->second);
}
}
// Clamp +/-inf values in the specified output tensors before metric evaluation.
if (!FLAGS_clamp_inf_outputs.empty()) {
const auto infClampNames = splitStringList(FLAGS_clamp_inf_outputs, ';');
for (const auto& name : infClampNames) {
const auto outIt = filteredOutputTensors.find(name);
const auto refIt = filteredReferenceTensors.find(name);
if (outIt == filteredOutputTensors.end() && refIt == filteredReferenceTensors.end()) {
std::cerr << "Warning: tensor '" << name
<< "' specified in --clamp_inf_outputs was not found in output tensors"
<< std::endl;
continue;
}
if (outIt != filteredOutputTensors.end()) {
if (!clampInfInTensor(outIt->second)) {
std::cerr << "Warning: tensor '" << name << "' has element type "
<< outIt->second.get_element_type()
<< " which is not supported for inf clamping, skipping" << std::endl;
continue;
}
}
if (refIt != filteredReferenceTensors.end()) {
clampInfInTensor(refIt->second);
}
}
}
using ResultStatus = std::tuple<std::string, int>;
std::array<ResultStatus, 2> resultStatuses{{{"FAILED", EXIT_FAILURE}, {"PASSED", EXIT_SUCCESS}}};
std::string mode(FLAGS_mode);
std::transform(mode.begin(), mode.end(), mode.begin(), [](unsigned char c) {
return std::tolower(c);
});
using TestMethod = std::function<bool(const TensorMap&, const TensorMap&, const LayoutMap&)>;
std::map<std::string, TestMethod> testMethods{
{{"classification", &testClassification},
{"cosim", &testCoSim},
{"mean_iou", &testMeanIoU},
{"nrmse", &testNRMSE},
{"l2norm", &testL2Norm},
{"raw", &testRAW},
{"rrmse", &testRRMSE},
{"map", &testMAP},
{"ssd",
[inputDescriptors](const TensorMap& oTensors,
const TensorMap& rTensors,
const LayoutMap& oLayouts) {
return testSSDDetection(oTensors, rTensors, inputDescriptors, oLayouts);
}},
{"yolo_v2",
[inputDescriptors](const TensorMap& oTensors,
const TensorMap& rTensors,
const LayoutMap& oLayouts) {
return testYoloV2(oTensors, rTensors, inputDescriptors, oLayouts);
}},
{"yolo_v3",
[inputDescriptors](const TensorMap& oTensors,
const TensorMap& rTensors,
const LayoutMap& oLayouts) {
return testYoloV3(oTensors, rTensors, inputDescriptors, oLayouts);
}},
{"yolo_v4",
[inputDescriptors](const TensorMap& oTensors,
const TensorMap& rTensors,
const LayoutMap& oLayouts) {
return testYoloV4(oTensors, rTensors, inputDescriptors, oLayouts);
}},
{"psnr",
[inputDescriptors](const TensorMap& oTensors,
const TensorMap& rTensors,
const LayoutMap& oLayouts) {
const auto& [firstOutputName, firstOutput] = *oTensors.begin();
const ov::Shape& shape = firstOutput.get_shape();
auto oAnyLayouts = transformLayoutDescriptionToAnyLayoutsMap(oLayouts);
const ov::Layout& outputLayout = oAnyLayouts.at(firstOutputName);
const size_t dstHeight = shape[ov::layout::height_idx(outputLayout)];
const size_t dstWidth = shape[ov::layout::width_idx(outputLayout)];
return testPSNR(oTensors, rTensors, static_cast<int>(dstHeight), static_cast<int>(dstWidth));
}}}};
// Compare the outputs with their references using the chosen metric
auto testMethodsIt = testMethods.find(mode);
if (testMethodsIt == testMethods.end()) {
std::cout << "Unknown mode " << FLAGS_mode << std::endl;
return EXIT_FAILURE;
}
auto testFunc = testMethodsIt->second;
auto [message, exitCode] = resultStatuses[testFunc(filteredOutputTensors, filteredReferenceTensors, filteredOutputLayouts)];
std::cout << message << std::endl;
return exitCode;
} else {
size_t outputInd = 0;
for (const auto& out : compiledModel.outputs()) {
const auto& tensor = outputTensors.at(out.get_any_name());
std::ostringstream ostr;
ostr << blobNamePrefix << "_ref_out_" << outputInd << "_case_" << numberOfTestCase << ".blob";
const auto blobFileName = ostr.str();
std::cout << "Dump reference output #" << outputInd << " to " << blobFileName << std::endl;
dumpTensor(tensor, blobFileName);
++outputInd;
}
}
}
} // try
catch (const std::exception& ex) {
std::cerr << "exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[]) {
utils::parseCommandLine(argc, argv);
return runSingleImageTest();
}