Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

10.1 KB
Raw Blame
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//

#pragma once

#include <filesystem>

#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"
#include "common_test_utils/unicode_utils.hpp"
#include "intel_npu/npu_private_properties.hpp"
#include "intel_npu/utils/logger/logger.hpp"
#include "intel_npu/utils/zero/zero_init.hpp"
#include "npu_test_env_cfg.hpp"
#include "openvino/core/log.hpp"
#include "openvino/runtime/core.hpp"
#include "openvino/runtime/intel_npu/properties.hpp"
#include "shared_test_classes/base/ov_behavior_test_utils.hpp"

std::string getBackendName(const ov::Core& core);

std::vector<std::string> getAvailableDevices(const ov::Core& core);

std::string modelPriorityToString(const ov::hint::Priority priority);

std::string removeDeviceNameOnlyID(const std::string& device_name_id);

std::shared_ptr<ov::Model> createModelWithStates(ov::element::Type type, const ov::Shape& shape);

template <typename C,
          typename = typename std::enable_if<(std::is_same<C, char>::value || std::is_same<C, wchar_t>::value)>::type>
void removeDirFilesRecursive(const std::basic_string<C>& path) {
    if (!ov::util::directory_exists(path)) {
        return;
    }
    for (const auto& entry : std::filesystem::directory_iterator(path)) {
        ov::test::utils::removeFile(entry.path().generic_string<C>());
    }
    ov::test::utils::removeDir(path);
    // EISW-105043: [Linux] [Bug] Cannot delete loaded shared libraries unicode directories
    // `Directory not empty` throw on linux for code below
    // std::filesystem::remove_all(path);
}

template <typename T>
std::string vectorToString(std::vector<T> v) {
    std::ostringstream res;
    for (size_t i = 0; i < v.size(); ++i) {
        if (i != 0) {
            res << ",";
        } else {
            res << "{";
        }
        res << v[i];
    }
    res << "}";
    return res.str();
}

// This utility class comes handy when OpenVino doesn't provide expicit `getTestCaseName`
// functions for declared test classes, but on NPU plugin side, we still need to append
// `_targetPlatform=NPUXXXX` to test name for activation of platform specific tests associated with test classes.
// Stands as a wrapper on `getTestCaseName` functions if declared and implements generic test name functions otherwise
// Programmer should NOT use this explicitly as it is part of `appendPlatformTypeTestName` utility.

struct GenericTestCaseNameClass {
    template <typename, typename = void>
    static constexpr bool hasGetTestCaseName = false;

    template <typename, typename = void>
    static constexpr bool has_get_test_case_name = false;

    template <typename T>
    static std::string getTestCaseName(const testing::TestParamInfo<typename T::ParamType>& obj) {
        if constexpr (hasGetTestCaseName<T>) {
            return T::getTestCaseName(obj);
        } else if constexpr (has_get_test_case_name<T>) {
            return T::get_test_case_name(obj);
        } else {
            std::ostringstream result;
            ::testing::PrintToStringParamName printToStringParamName;
            result << printToStringParamName(obj);
            return result.str();
        }
    }
};

template <typename T>
constexpr bool GenericTestCaseNameClass::hasGetTestCaseName<
    T,
    std::void_t<decltype(T::getTestCaseName(std::declval<testing::TestParamInfo<typename T::ParamType>>()))>> = true;

template <typename T>
constexpr bool GenericTestCaseNameClass::has_get_test_case_name<
    T,
    std::void_t<decltype(T::get_test_case_name(std::declval<testing::TestParamInfo<typename T::ParamType>>()))>> = true;

namespace ov::test::behavior {
inline std::shared_ptr<ov::Model> getDefaultNGraphFunctionForTheDeviceNPU(
    std::vector<size_t> inputShape = {1, 2, 32, 32},
    ov::element::Type_t ngPrc = ov::element::Type_t::f32) {
    return ov::test::utils::make_conv_pool_relu(inputShape, ngPrc);
}

class OVInferRequestTestsNPU : public OVInferRequestTests {
public:
    void SetUp() override {
        SKIP_IF_CURRENT_TEST_IS_DISABLED();

        std::tie(target_device, configuration) = this->GetParam();
        APIBaseTest::SetUp();
        function = ov::test::behavior::getDefaultNGraphFunctionForTheDeviceNPU();
        ov::AnyMap params;
        for (auto&& v : configuration) {
            params.emplace(v.first, v.second);
        }
        execNet = core->compile_model(function, target_device, params);
    }
};
}  // namespace ov::test::behavior

namespace ov {

namespace test {

namespace utils {

template <typename T, bool COUNTER = false>
std::string appendPlatformTypeTestName(const testing::TestParamInfo<typename T::ParamType>& obj) {
    std::string test_name = GenericTestCaseNameClass::getTestCaseName<T>(obj);
    if constexpr (COUNTER == true) {  // used only when test name duplication has justification
        static size_t testCounter = 0;
        test_name += "_testCounter=" + std::to_string(testCounter++);
    }
    return test_name + "_targetPlatform=" + getTestsPlatformFromEnvironmentOr(ov::test::utils::DEVICE_NPU);
}

class DefaultAllocatorNotAligned final {
public:
    void* allocate(const size_t bytes, const size_t alignment = 4096) {
        auto handle = (::operator new(bytes + _offset, std::align_val_t(alignment)));
        return static_cast<uint8_t*>(handle) + _offset;
    }
    void deallocate(void* handle, const size_t bytes, size_t alignment = 4096) noexcept {
        ::operator delete(static_cast<uint8_t*>(handle) - _offset, std::align_val_t(alignment));
    }
    bool is_equal(const DefaultAllocatorNotAligned&) const {
        return false;
    }

private:
    size_t _offset = 16;
};

class DefaultAllocatorAligned final {
public:
    void* allocate(const size_t bytes, const size_t) {
        return ::operator new(bytes, std::align_val_t(4096));
    }
    void deallocate(void* handle, const size_t, size_t) noexcept {
        ::operator delete(static_cast<uint8_t*>(handle), std::align_val_t(4096));
    }
    bool is_equal(const DefaultAllocatorAligned&) const {
        return false;
    }
};

std::tuple</* importMemoryBatched */ ov::Tensor,
           /* importMemoryTensor_1 */ ov::Tensor,
           /* importMemoryTensor_2 */ ov::Tensor,
           /* unalignedBatchedTensor */ ov::Tensor,
           /* unalignedTensor_1 */ ov::Tensor,
           /* unalignedTensor_2 */ ov::Tensor>
allocate_tensors(const std::shared_ptr<ov::Model>& model, const ov::element::Type& element_type);

template <typename T, typename U>
void set_tensor_and_infer(const std::shared_ptr<T>& infer_request,
                          const bool should_infer,
                          const bool withResetInferRequest,
                          const ov::Output<const ov::Node>& port,
                          const U& tensor,
                          const std::function<void(void)>& reset_cb) {
    infer_request->set_tensor(port, tensor);
    if (should_infer) {
        infer_request->infer();
    }

    if (withResetInferRequest) {
        reset_cb();
    }
};

template <typename T, typename U>
void set_tensors_and_infer(const std::shared_ptr<T>& infer_request,
                           const bool should_infer,
                           const bool withResetInferRequest,
                           const ov::Output<const ov::Node>& port,
                           const std::vector<U>& tensors,
                           const std::function<void(void)>& reset_cb) {
    infer_request->set_tensors(port, tensors);
    if (should_infer) {
        infer_request->infer();
    }

    if (withResetInferRequest) {
        reset_cb();
    }
};

class LogCallbackGuard {
public:
    explicit LogCallbackGuard(const std::function<void(std::string_view)>& callback) {
        ov::util::set_log_callback(callback);
    }

    ~LogCallbackGuard() {
        ov::util::reset_log_callback();
    }

    LogCallbackGuard(const LogCallbackGuard&) = delete;
    LogCallbackGuard& operator=(const LogCallbackGuard&) = delete;
};

class LoggerLevelGuard {
public:
    explicit LoggerLevelGuard(ov::log::Level level) : _previousLevel(::intel_npu::Logger::global().level()) {
        ::intel_npu::Logger::global().setLevel(level);
    }

    ~LoggerLevelGuard() {
        ::intel_npu::Logger::global().setLevel(_previousLevel);
    }

    LoggerLevelGuard(const LoggerLevelGuard&) = delete;
    LoggerLevelGuard& operator=(const LoggerLevelGuard&) = delete;

private:
    ov::log::Level _previousLevel;
};

// Returns a copy of configs with extraProperties merged into every entry; keys already present in
// an entry are overwritten by extraProperties.
inline std::vector<ov::AnyMap> mergeConfigs(std::vector<ov::AnyMap> configs, const ov::AnyMap& extraProperties) {
    for (auto& config : configs) {
        for (const auto& property : extraProperties) {
            config[property.first] = property.second;
        }
    }
    return configs;
}

inline const ov::AnyMap quietCompilerLogsConfig = {ov::intel_npu::compile_log_level(ov::log::Level::ERR),
                                                   ov::log::level(ov::log::Level::ERR)};

inline bool isDefaultDriverCompiler(const std::string& target_device) {
    ov::Core core;
    auto compiler_type = core.get_property(target_device, ov::intel_npu::compiler_type);
    if (compiler_type == ov::intel_npu::CompilerType::DRIVER) {
        return true;
    }
    return false;
}

inline bool isGraphExtVersionLowerThan(uint32_t major, uint32_t minor) {
    const auto graph_ext_version = ::intel_npu::ZeroInitStructsHolder::getInstance()->getGraphDdiTable().version();
    const auto required_version = ZE_MAKE_VERSION(major, minor);
    return graph_ext_version < required_version;
}

#define NPU_SKIP_IF_GRAPH_EXT_LOWER_THAN(major, minor)                                                    \
    {                                                                                                     \
        if (ov::test::utils::isGraphExtVersionLowerThan(major, minor)) {                                  \
            GTEST_SKIP() << "Test skipped because L0 graph ext version is lower than " #major "." #minor; \
        }                                                                                                 \
    }

}  // namespace utils

}  // namespace test

}  // namespace ov