Skip to content

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

Memcheck Windows GPU memory sampling (#33800)

Egor Tyuvaev685c93116f92
diff --git a/tests/memory_tests/CMakeLists.txt b/tests/memory_tests/CMakeLists.txt
index 171272c562f..4826b807248 100644
--- a/tests/memory_tests/CMakeLists.txt
+++ b/tests/memory_tests/CMakeLists.txt
@@ -4,13 +4,15 @@
cmake_minimum_required(VERSION 3.14)
+set (CMAKE_CXX_STANDARD 17)
+
if(NOT TARGET openvino::runtime)
find_package(OpenVINO REQUIRED)
endif()
function(add_test)
set(target "test_${ARGV0}")
- add_executable(${target} "src/${target}.cpp")
+ add_executable(${target} "src/${target}.cpp" "src/system_memory_sampling.cpp" "src/gpu_memory_sampling.cpp")
target_link_libraries(${target} openvino::runtime)
target_compile_definitions(${target} PUBLIC TEST_NAME=${ARGV0})
install(TARGETS ${target} DESTINATION tests/memory_tests COMPONENT tests EXCLUDE_FROM_ALL)
diff --git a/tests/memory_tests/src/gpu_memory_sampling.cpp b/tests/memory_tests/src/gpu_memory_sampling.cpp
new file mode 100644
index 00000000000..5fe524093c7
--- /dev/null
+++ b/tests/memory_tests/src/gpu_memory_sampling.cpp
@@ -0,0 +1,103 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <iostream>
+#include "gpu_memory_sampling.hpp"
+
+#define INTEL_PCI_VENDOR_ID 0x8086
+
+#ifdef _WIN32
+
+#include <windows.h>
+#include <wrl/client.h>
+#include <dxgi1_4.h>
+#pragma comment(lib, "dxgi.lib")
+
+namespace memory_tests::gpu {
+
+using Microsoft::WRL::ComPtr;
+
+static ComPtr<IDXGIFactory4> dxgi_factory;
+static ComPtr<IDXGIAdapter3> selected_adapter;
+
+
+InitStatus init() {
+ if (S_OK != CreateDXGIFactory2(0, IID_PPV_ARGS(&dxgi_factory))) {
+ std::cerr << "CreateDXGIFactory2 failed" << std::endl;
+ return InitStatus::SUBSYSTEM_UNAVAILABLE;
+ }
+ IDXGIAdapter *adapter = nullptr;
+ for (
+ UINT adapterIndex = 0;
+ dxgi_factory->EnumAdapters(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND;
+ adapterIndex += 1
+ ) {
+ DXGI_ADAPTER_DESC desc;
+ adapter->GetDesc(&desc);
+ if (desc.VendorId == INTEL_PCI_VENDOR_ID) {
+ // at this moment only looking for the first Intel GPU
+ std::cerr << "Selecting adapter " << std::hex << desc.DeviceId << std::dec << std::endl;
+ if (S_OK != adapter->QueryInterface(IID_PPV_ARGS(&selected_adapter))) {
+ std::cerr << "Failed to query IDXGIAdapter3 interface for selected adapter" << std::endl;
+ return InitStatus::SUBSYSTEM_UNSUPPORTED;
+ }
+ adapter->Release();
+ return InitStatus::SUCCESS;
+ }
+ adapter->Release();
+ }
+
+ std::cerr << "No proper adapter was found for sampling" << std::endl;
+ return InitStatus::GPU_NOT_FOUND;
+}
+
+Sample sample() {
+ const int KiB = 1024;
+ DXGI_ADAPTER_DESC desc;
+ selected_adapter->GetDesc(&desc);
+
+ Sample sample;
+ sample.local_used = 0;
+ sample.local_total = (desc.DedicatedVideoMemory + desc.DedicatedSystemMemory) / KiB;
+ sample.nonlocal_used = 0;
+ sample.nonlocal_total = desc.SharedSystemMemory / KiB;
+
+ int nodeId = 0;
+ DXGI_QUERY_VIDEO_MEMORY_INFO info;
+ while (true) {
+ auto result = selected_adapter->QueryVideoMemoryInfo(
+ nodeId, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &info);
+ if (result != S_OK) {
+ break;
+ }
+ sample.local_used += info.CurrentUsage / KiB;
+
+ result = selected_adapter->QueryVideoMemoryInfo(
+ nodeId, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &info);
+ if (result != S_OK) {
+ break;
+ }
+ sample.nonlocal_used += info.CurrentUsage / KiB;
+ nodeId += 1;
+ }
+ return sample;
+}
+
+} // namespace memory_tests::gpu
+
+#else
+
+namespace memory_tests::gpu {
+
+InitStatus init() {
+ return InitStatus::SUBSYSTEM_UNAVAILABLE;
+}
+
+Sample sample() {
+ return {};
+}
+
+} // namespace memory_tests::gpu
+
+#endif
diff --git a/tests/memory_tests/src/gpu_memory_sampling.hpp b/tests/memory_tests/src/gpu_memory_sampling.hpp
new file mode 100644
index 00000000000..905d8c9c88e
--- /dev/null
+++ b/tests/memory_tests/src/gpu_memory_sampling.hpp
@@ -0,0 +1,31 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <cstdint>
+
+
+namespace memory_tests::gpu {
+
+struct Sample {
+ // memory size in kb
+ int64_t local_used = -1;
+ int64_t local_total = -1;
+ int64_t nonlocal_used = -1;
+ int64_t nonlocal_total = -1;
+};
+
+
+enum class InitStatus {
+ SUCCESS,
+ SUBSYSTEM_UNAVAILABLE,
+ SUBSYSTEM_UNSUPPORTED,
+ GPU_NOT_FOUND,
+};
+
+
+InitStatus init();
+
+Sample sample();
+
+} // namespace memory_tests::gpu
diff --git a/tests/memory_tests/src/memory_test.hpp b/tests/memory_tests/src/memory_test.hpp
index e3dd105b99a..b3a273d9f3d 100644
--- a/tests/memory_tests/src/memory_test.hpp
+++ b/tests/memory_tests/src/memory_test.hpp
@@ -3,17 +3,27 @@
//
#include <stdint.h>
+#include <stdexcept>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
+#include "system_memory_sampling.hpp"
+#include "gpu_memory_sampling.hpp"
+
#define _AS_STR(x) #x
#define AS_STR(x) _AS_STR(x)
-struct MemoryCounters {
+// To be defined in the test
+std::vector<std::string> test_samples();
+
+
+namespace memory_tests {
+
+struct Counters {
// memory size in kb
int64_t virtual_size = -1;
int64_t virtual_peak = -1;
@@ -22,99 +32,13 @@ struct MemoryCounters {
int32_t thread_count = -1;
- static MemoryCounters sample();
+ int64_t gpu_local_used = -1;
+ int64_t gpu_local_total = -1;
+ int64_t gpu_nonlocal_used = -1;
+ int64_t gpu_nonlocal_total = -1;
};
-#ifdef _WIN32
-
-#include <windows.h>
-#include <tlhelp32.h>
-#include <psapi.h>
-
-static PROCESS_MEMORY_COUNTERS getMemoryInfo() {
- static PROCESS_MEMORY_COUNTERS pmc;
- pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
- if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, pmc.cb))
- throw std::runtime_error("Can't get system memory values");
- return pmc;
-}
-
-static size_t getThreadsNum() {
- // first determine the id of the current process
- DWORD const id = GetCurrentProcessId();
-
- // then get a process list snapshot.
- HANDLE const snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 );
-
- // initialize the process entry structure.
- PROCESSENTRY32 entry = { 0 };
- entry.dwSize = sizeof( entry );
-
- // get the first process info.
- BOOL ret = true;
- ret = Process32First( snapshot, &entry );
- while( ret && entry.th32ProcessID != id ) {
- ret = Process32Next( snapshot, &entry );
- }
- CloseHandle( snapshot );
- return ret
- ? entry.cntThreads
- : -1;
-}
-
-MemoryCounters MemoryCounters::sample() {
- MemoryCounters out;
- auto meminfo = getMemoryInfo();
- out.virtual_size = meminfo.PagefileUsage / 1024;
- out.virtual_peak = meminfo.PeakPagefileUsage / 1024;
- out.resident_size = meminfo.WorkingSetSize / 1024;
- out.resident_peak = meminfo.PeakWorkingSetSize / 1024;
- out.thread_count = (int32_t) getThreadsNum();
- return out;
-}
-
-#else
-
-MemoryCounters MemoryCounters::sample() {
- MemoryCounters out;
- std::ifstream file;
- file.open("/proc/self/status");
- std::string line;
- while (true) {
- if (!std::getline(file, line)) {
- break;
- }
- auto delim_pos = line.find(':');
- if (delim_pos == std::string::npos) {
- continue;
- }
- auto prefix = line.substr(0, delim_pos);
- auto value_start = line.find_first_not_of("\t ", delim_pos + 1);
- auto value_end = line.find_first_of("\t ", value_start);
- if (value_start == std::string::npos) {
- continue;
- }
- auto value = line.substr(value_start, value_end - value_start);
- long ivalue = std::atol(value.c_str());
- if (prefix == "VmSize") {
- out.virtual_size = ivalue;
- } else if (prefix == "VmPeak") {
- out.virtual_peak = ivalue;
- } else if (prefix == "VmRSS") {
- out.resident_size = ivalue;
- } else if (prefix == "VmHWM") {
- out.resident_peak = ivalue;
- } else if (prefix == "Threads") {
- out.thread_count = (int32_t) ivalue;
- }
- }
- return out;
-}
-
-#endif
-
-
inline std::string jsonescape(const std::string &str) {
std::string newstr;
newstr.reserve(str.size() * 2);
@@ -145,9 +69,6 @@ inline std::string jsonescape(const std::string &str) {
}
-// To be defined in the test
-std::vector<std::string> test_samples();
-
std::vector<std::string> registered_samples_init() {
auto samples = test_samples();
samples.emplace_back("unload");
@@ -157,12 +78,14 @@ std::vector<std::string> registered_samples_init() {
static std::vector<std::string> registered_samples = registered_samples_init();
-struct TestContext {
+struct Context {
std::string model_path;
std::string device;
- std::vector<std::pair<std::string, MemoryCounters>> samples;
+ bool gpu_ready = false;
- static TestContext from_args(int argc, char **argv) {
+ std::vector<std::pair<std::string, Counters>> samples;
+
+ static Context from_args(int argc, char **argv) {
std::string model_path;
std::string device = "CPU";
@@ -177,7 +100,16 @@ struct TestContext {
device = argv[2];
}
- return {model_path, device};
+ bool gpu_ready = false;
+ if (device.find("GPU") != std::string::npos) {
+ // GPU is used -> initialize GPU sampling
+ gpu_ready = gpu::init() == gpu::InitStatus::SUCCESS;
+ if (!gpu_ready) {
+ std::cerr << "GPU memory sampling will not be available" << std::endl;
+ }
+ }
+
+ return {model_path, device, gpu_ready};
}
bool is_sample_registered(std::string &sample_name) {
@@ -196,7 +128,21 @@ struct TestContext {
std::string error_msg = "sample \"" + sample_name + "\" is not defined in registered_samples";
throw std::runtime_error(error_msg);
}
- samples.emplace_back(std::move(sample_name), MemoryCounters::sample());
+ auto sys_sample = system::sample();
+ auto sample = Counters();
+ sample.virtual_size = sys_sample.virtual_size;
+ sample.virtual_peak = sys_sample.virtual_peak;
+ sample.resident_size = sys_sample.resident_size;
+ sample.resident_peak = sys_sample.resident_peak;
+ sample.thread_count = sys_sample.thread_count;
+ if (gpu_ready) {
+ auto gpu_sample = gpu::sample();
+ sample.gpu_local_used = gpu_sample.local_used;
+ sample.gpu_local_total = gpu_sample.local_total;
+ sample.gpu_nonlocal_used = gpu_sample.nonlocal_used;
+ sample.gpu_nonlocal_total = gpu_sample.nonlocal_total;
+ }
+ samples.push_back({sample_name, sample});
}
void report() {
@@ -211,7 +157,11 @@ struct TestContext {
<< "\"vmpeak\": " << sample.second.virtual_peak << ", "
<< "\"vmrss\": " << sample.second.resident_size << ", "
<< "\"vmhwm\": " << sample.second.resident_peak << ", "
- << "\"threads\": " << sample.second.thread_count << "}";
+ << "\"threads\": " << sample.second.thread_count << ", "
+ << "\"gpu_local_used\": " << sample.second.gpu_local_used << ", "
+ << "\"gpu_local_total\": " << sample.second.gpu_local_total << ", "
+ << "\"gpu_nonlocal_used\": " << sample.second.gpu_nonlocal_used << ", "
+ << "\"gpu_nonlocal_total\": " << sample.second.gpu_nonlocal_total << "}";
if (&sample != &samples.back()) {
std::cout << ", ";
}
@@ -220,17 +170,19 @@ struct TestContext {
}
};
+} // namespace memory_tests
+
// To be defined in the test
-void do_test(TestContext &test);
+void do_test(memory_tests::Context &test);
int main(int argc, char **argv) {
if (argc == 2 && std::string("--info") == argv[1]) {
std::cout << "TEST_INFO: {\"samples\": [";
- for (auto &sample_name: registered_samples) {
+ for (auto &sample_name: memory_tests::registered_samples) {
std::cout << "\"" << sample_name << "\"";
- if (&sample_name != &registered_samples.back()) {
+ if (&sample_name != &memory_tests::registered_samples.back()) {
std::cout << ", ";
}
}
@@ -238,7 +190,7 @@ int main(int argc, char **argv) {
return 0;
}
- TestContext test = TestContext::from_args(argc, argv);
+ auto test = memory_tests::Context::from_args(argc, argv);
do_test(test);
test.sample("unload");
test.report();
diff --git a/tests/memory_tests/src/system_memory_sampling.cpp b/tests/memory_tests/src/system_memory_sampling.cpp
new file mode 100644
index 00000000000..fad6b20825b
--- /dev/null
+++ b/tests/memory_tests/src/system_memory_sampling.cpp
@@ -0,0 +1,107 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "system_memory_sampling.hpp"
+
+
+#ifdef _WIN32
+
+#include <stdexcept>
+#include <windows.h>
+#include <tlhelp32.h>
+#include <psapi.h>
+
+namespace memory_tests::system {
+
+static PROCESS_MEMORY_COUNTERS getMemoryInfo() {
+ static PROCESS_MEMORY_COUNTERS pmc;
+ pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
+ if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, pmc.cb))
+ throw std::runtime_error("Can't get system memory values");
+ return pmc;
+}
+
+static size_t getThreadsNum() {
+ // first determine the id of the current process
+ DWORD const id = GetCurrentProcessId();
+
+ // then get a process list snapshot.
+ HANDLE const snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 );
+
+ // initialize the process entry structure.
+ PROCESSENTRY32 entry = { 0 };
+ entry.dwSize = sizeof( entry );
+
+ // get the first process info.
+ BOOL ret = true;
+ ret = Process32First( snapshot, &entry );
+ while( ret && entry.th32ProcessID != id ) {
+ ret = Process32Next( snapshot, &entry );
+ }
+ CloseHandle( snapshot );
+ return ret
+ ? entry.cntThreads
+ : -1;
+}
+
+
+Sample sample() {
+ Sample out;
+ auto meminfo = getMemoryInfo();
+ out.virtual_size = meminfo.PagefileUsage / 1024;
+ out.virtual_peak = meminfo.PeakPagefileUsage / 1024;
+ out.resident_size = meminfo.WorkingSetSize / 1024;
+ out.resident_peak = meminfo.PeakWorkingSetSize / 1024;
+ out.thread_count = (int32_t) getThreadsNum();
+ return out;
+}
+
+} // namespace memory_tests::system
+
+#else
+
+#include <fstream>
+#include <string>
+
+namespace memory_tests::system {
+
+Sample sample() {
+ Sample out;
+ std::ifstream file;
+ file.open("/proc/self/status");
+ std::string line;
+ while (true) {
+ if (!std::getline(file, line)) {
+ break;
+ }
+ auto delim_pos = line.find(':');
+ if (delim_pos == std::string::npos) {
+ continue;
+ }
+ auto prefix = line.substr(0, delim_pos);
+ auto value_start = line.find_first_not_of("\t ", delim_pos + 1);
+ auto value_end = line.find_first_of("\t ", value_start);
+ if (value_start == std::string::npos) {
+ continue;
+ }
+ auto value = line.substr(value_start, value_end - value_start);
+ long ivalue = std::atol(value.c_str());
+ if (prefix == "VmSize") {
+ out.virtual_size = ivalue;
+ } else if (prefix == "VmPeak") {
+ out.virtual_peak = ivalue;
+ } else if (prefix == "VmRSS") {
+ out.resident_size = ivalue;
+ } else if (prefix == "VmHWM") {
+ out.resident_peak = ivalue;
+ } else if (prefix == "Threads") {
+ out.thread_count = (int32_t) ivalue;
+ }
+ }
+ return out;
+}
+
+} // namespace memory_tests::system
+
+#endif
diff --git a/tests/memory_tests/src/system_memory_sampling.hpp b/tests/memory_tests/src/system_memory_sampling.hpp
new file mode 100644
index 00000000000..ccb600bbcaf
--- /dev/null
+++ b/tests/memory_tests/src/system_memory_sampling.hpp
@@ -0,0 +1,23 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <cstdint>
+
+
+namespace memory_tests::system {
+
+struct Sample {
+ // memory size in kb
+ int64_t virtual_size = -1;
+ int64_t virtual_peak = -1;
+ int64_t resident_size = -1;
+ int64_t resident_peak = -1;
+
+ int32_t thread_count = -1;
+};
+
+
+Sample sample();
+
+} // namespace memory_tests::system
diff --git a/tests/memory_tests/src/test_inference_async.cpp b/tests/memory_tests/src/test_inference_async.cpp
index fcc7ecd72c9..3934c38c907 100644
--- a/tests/memory_tests/src/test_inference_async.cpp
+++ b/tests/memory_tests/src/test_inference_async.cpp
@@ -17,7 +17,7 @@ std::vector<std::string> test_samples() {
}
-void do_test(TestContext &test) {
+void do_test(memory_tests::Context &test) {
test.sample("start");
ov::Core core;
diff --git a/tests/memory_tests/src/test_inference_sync.cpp b/tests/memory_tests/src/test_inference_sync.cpp
index 4098d05eabb..fa82f48e098 100644
--- a/tests/memory_tests/src/test_inference_sync.cpp
+++ b/tests/memory_tests/src/test_inference_sync.cpp
@@ -17,7 +17,7 @@ std::vector<std::string> test_samples() {
}
-void do_test(TestContext &test) {
+void do_test(memory_tests::Context &test) {
test.sample("start");
ov::Core core;
diff --git a/tests/memory_tests/tools/run_tests.py b/tests/memory_tests/tools/run_tests.py
index 905afe3f918..071dc373edc 100644
--- a/tests/memory_tests/tools/run_tests.py
+++ b/tests/memory_tests/tools/run_tests.py
@@ -47,34 +47,43 @@ class MemSample:
vmrss: int
vmhwm: int
threads: int
-
- as_dict = asdict
-
- @staticmethod
- def from_dict(values: dict):
+ gpu_local_used: int = -1
+ gpu_local_total: int = -1
+ gpu_nonlocal_used: int = -1
+ gpu_nonlocal_total: int = -1
+
+ def as_dict(self):
+ def to_camel_case(s: str):
+ first, *others = s.split("_")
+ return "".join([first, *[x.capitalize() for x in others]])
+
+ return {
+ to_camel_case(k): v
+ for k, v in asdict(self).items()
+ }
+
+ @classmethod
+ def from_dict(cls, values: dict):
class_fields = MemSample.__dataclass_fields__.keys()
- selected_values = {k: int(values[k]) for k in class_fields}
+ selected_values = {
+ k: int(values[k])
+ for k in class_fields
+ }
return MemSample(**selected_values)
- def compare(self, reference: "MemSample"):
- ref_dict = reference.as_dict()
- for key, value in self.as_dict().items():
- refval = ref_dict[key]
- yield (key, *value_diff(value, refval))
-
def __repr__(self):
return "; ".join(f"{k} {v:>10}" for k, v in self.as_dict().items())
def run_test_executable_extract_result(command):
- proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ proc = subprocess.run(command, stdout=subprocess.PIPE)
run_out = proc.stdout.decode()
if run_out.startswith("TEST_RESULTS: "):
results_json = run_out.splitlines()[0].removeprefix("TEST_RESULTS: ")
results = json.loads(results_json)
if "samples" in results:
results["samples"] = {
- sname: MemSample(**sample)
+ sname: MemSample.from_dict(sample)
for sname, sample in results["samples"].items()
}
return results
@@ -260,7 +269,7 @@ if __name__ == "__main__":
'must not intersect')
parser.add_argument("--devices", default="CPU")
- parser.add_argument("--api", help="API endpoint for results to compare and upload")
+ parser.add_argument("--api", help="API endpoint for results to upload")
parser.add_argument("--upload-reference", "--upload_reference",
"--upload-references", "--upload_references", action="store_true",
help="This run will make new reference values")