Skip to content

Commit 726dbe7

Browse files
author
Gin
committed
adding memory usage on macOS and fix Model Cache path
1 parent 0527744 commit 726dbe7

File tree

13 files changed

+152
-14
lines changed

13 files changed

+152
-14
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <iostream>
2+
3+
#if defined(__linux) || defined(__APPLE__)
4+
// get process memory and total system memory for Linux and macOS
5+
#include <libproc.h>
6+
#include <sys/proc_info.h>
7+
#include <unistd.h> // For getpid()
8+
#endif
9+
10+
#if defined(__APPLE__)
11+
// get total used system memory for macOS
12+
#include <mach/mach_host.h>
13+
#include <mach/vm_statistics.h>
14+
#endif
15+
16+
#include "MemoryUtilization.h"
17+
18+
namespace PokemonAutomation{
19+
20+
21+
22+
void print_macos_total_used_memory() {
23+
24+
}
25+
26+
27+
MemoryUsage process_memory_usage(){
28+
MemoryUsage usage;
29+
30+
#if defined(__linux) || defined(__APPLE__)
31+
pid_t pid = getpid();
32+
struct proc_taskinfo task_info;
33+
int ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &task_info, sizeof(task_info));
34+
35+
if (ret <= 0) {
36+
std::cerr << "Error getting process info for PID " << pid << ": " << strerror(errno) << std::endl;
37+
return usage;
38+
}
39+
40+
usage.process_physical_memory = task_info.pti_resident_size;
41+
usage.process_virtual_memory = task_info.pti_virtual_size;
42+
usage.total_system_memory = task_info.pti_total_system;
43+
44+
#if defined(__APPLE__) // compute total used system memory on macOS
45+
vm_size_t page_size;
46+
vm_statistics_data_t vm_stats;
47+
mach_port_t mach_port = mach_host_self();
48+
mach_msg_type_number_t count = sizeof(vm_stats) / sizeof(integer_t);
49+
50+
// Get the host statistics
51+
if (KERN_SUCCESS != host_statistics(mach_port, HOST_VM_INFO, (host_info_t)&vm_stats, &count)) {
52+
std::cerr << "Failed to get host statistics." << std::endl;
53+
return usage;
54+
}
55+
// Get the system's page size
56+
host_page_size(mach_port, &page_size);
57+
58+
// Calculate used memory from vm_statistics
59+
// Used memory = Wired + Active + Inactive
60+
size_t wired_pages = vm_stats.wire_count;
61+
size_t active_pages = vm_stats.active_count;
62+
size_t inactive_pages = vm_stats.inactive_count;
63+
64+
usage.total_used_system_memory = (wired_pages + active_pages + inactive_pages) * page_size;
65+
#else // compute total used system memory on Linux
66+
// TODO
67+
#endif
68+
69+
#else // compute memory info on Windows
70+
// TODO
71+
#endif
72+
return usage;
73+
}
74+
75+
76+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* Memory Utilization
2+
*
3+
* From: https://github.com/PokemonAutomation/
4+
*
5+
*/
6+
7+
#ifndef PokemonAutomation_MemoryUtilization_H
8+
#define PokemonAutomation_MemoryUtilization_H
9+
10+
#include <cstddef>
11+
12+
namespace PokemonAutomation{
13+
14+
15+
struct MemoryUsage{
16+
size_t total_system_memory = 0; // in bytes
17+
size_t total_used_system_memory = 0; // in bytes
18+
size_t process_physical_memory = 0; // in bytes
19+
size_t process_virtual_memory = 0; // in bytes
20+
};
21+
22+
23+
MemoryUsage process_memory_usage();
24+
25+
26+
}
27+
28+
29+
#endif

SerialPrograms/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ file(GLOB MAIN_SOURCES
146146
../Common/Cpp/LifetimeSanitizer.cpp
147147
../Common/Cpp/LifetimeSanitizer.h
148148
../Common/Cpp/ListenerSet.h
149+
../Common/Cpp/MemoryUtilization/MemoryUtilization.cpp
150+
../Common/Cpp/MemoryUtilization/MemoryUtilization.h
149151
../Common/Cpp/Options/BatchOption.cpp
150152
../Common/Cpp/Options/BatchOption.h
151153
../Common/Cpp/Options/BooleanCheckBoxOption.cpp

SerialPrograms/Source/CommonFramework/Globals.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,5 +205,10 @@ const std::string& ML_ANNOTATION_PATH(){
205205
return path;
206206
}
207207

208+
const std::string& ML_MODEL_CACHE_PATH(){
209+
static const std::string path = RUNTIME_BASE_PATH() + "ModelCache/";
210+
return path;
211+
}
212+
208213
}
209214

SerialPrograms/Source/CommonFramework/Globals.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ const std::string& TRAINING_PATH();
6262

6363
// Folder path (end with "/") to hold data annotation for ML labeling programs
6464
const std::string& ML_ANNOTATION_PATH();
65+
// Folder path (end with "/") to hold model cache for model inferences. This is only used on macOS
66+
// for the Apple CoreML model acceleration framework can create model cache for faster model inference
67+
// sessions.
68+
const std::string& ML_MODEL_CACHE_PATH();
6569

6670

6771
enum class ProgramState{

SerialPrograms/Source/CommonFramework/Main.cpp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ int main(int argc, char *argv[]){
8585
return 1;
8686
}
8787

88-
std::cout << "Loading from program setting JSON: " << PROGRAM_SETTING_JSON_PATH() << std::endl;
8988
PERSISTENT_SETTINGS().read();
9089

9190
if (!migrate_stats(logger)){

SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <opencv2/imgcodecs.hpp>
1515
#include <opencv2/imgproc.hpp>
1616
#include "3rdParty/ONNX/OnnxToolsPA.h"
17+
#include "CommonFramework/Globals.h"
1718
#include "ML/Models/ML_ONNXRuntimeHelpers.h"
1819
#include "ML_SegmentAnythingModelConstants.h"
1920
#include "ML_SegmentAnythingModel.h"
@@ -24,7 +25,8 @@ namespace ML{
2425

2526

2627
SAMEmbedderSession::SAMEmbedderSession(const std::string& model_path)
27-
: session{create_session(model_path, "SAMEmbedder")}
28+
: m_session_options{create_session_options(ML_MODEL_CACHE_PATH() + "SAMEmbedder/")}
29+
, session{create_session(m_env, m_session_options, model_path, ML_MODEL_CACHE_PATH() + "SAMEmbedder/")}
2830
, memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)}
2931
, input_names{session.GetInputNames()}
3032
, output_names{session.GetOutputNames()}
@@ -63,7 +65,8 @@ void SAMEmbedderSession::run(cv::Mat& input_image, std::vector<float>& model_out
6365

6466

6567
SAMSession::SAMSession(const std::string& model_path)
66-
: session{create_session(model_path, "SAM")}
68+
: m_session_options{create_session_options(ML_MODEL_CACHE_PATH() + "SAM/")}
69+
, session{create_session(m_env, m_session_options, model_path, ML_MODEL_CACHE_PATH() + "SAM/")}
6770
, memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)}
6871
, input_names{session.GetInputNames()}
6972
, output_names{session.GetOutputNames()}

SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ class SAMEmbedderSession{
3636
void run(cv::Mat& input_image, std::vector<float>& output_image_embedding);
3737

3838
private:
39+
Ort::Env m_env;
40+
Ort::SessionOptions m_session_options;
3941
Ort::Session session;
4042
Ort::MemoryInfo memory_info;
4143
Ort::RunOptions run_options;
@@ -69,6 +71,8 @@ class SAMSession{
6971
const std::vector<int>& input_box,
7072
std::vector<bool>& output_boolean_mask);
7173
private:
74+
Ort::Env m_env;
75+
Ort::SessionOptions m_session_options;
7276
Ort::Session session;
7377
Ort::MemoryInfo memory_info;
7478
Ort::RunOptions run_options;

SerialPrograms/Source/ML/Models/ML_ONNXRuntimeHelpers.cpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ namespace fs = std::filesystem;
2424
namespace PokemonAutomation{
2525
namespace ML{
2626

27-
const char* MODEL_CACHE_FOLDER = "./ModelCache/";
2827

2928
// Computes the cryptographic hash of a file.
3029
std::string create_file_hash(const std::string& filepath){
@@ -52,6 +51,7 @@ Ort::SessionOptions create_session_options(const std::string& model_cache_path){
5251
// "NeuralNetwork" is a faster ModelFormat than "MLProgram".
5352
provider_options["ModelFormat"] = std::string("NeuralNetwork");
5453
provider_options["ModelCacheDirectory"] = model_cache_path;
54+
5555
// provider_options["MLComputeUnits"] = "ALL";
5656
// provider_options["RequireStaticInputShapes"] = "0";
5757
// provider_options["EnableOnSubgraphs"] = "0";
@@ -113,14 +113,13 @@ void write_cache_flag_file(const std::string& model_cache_path, const std::strin
113113
}
114114

115115

116-
Ort::Session create_session(const std::string& model_path, const std::string& cache_folder_name){
117-
const std::string model_cache_path = MODEL_CACHE_FOLDER + cache_folder_name;
118-
Ort::SessionOptions so = create_session_options(model_cache_path);
116+
Ort::Session create_session(const Ort::Env& env, const Ort::SessionOptions& so,
117+
const std::string& model_path, const std::string& model_cache_path)
118+
{
119119
bool write_flag_file = true;
120120
std::string file_hash;
121121
std::tie(write_flag_file, file_hash) = clean_up_old_model_cache(model_cache_path, model_path);
122122

123-
Ort::Env env;
124123
Ort::Session session{env, str_to_onnx_str(model_path).c_str(), so};
125124
// when Ort::Ssssion is created, if possible, it will create a model cache
126125
if (write_flag_file){

SerialPrograms/Source/ML/Models/ML_ONNXRuntimeHelpers.h

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@
1616
namespace PokemonAutomation{
1717
namespace ML{
1818

19-
// Create an ONNX Session.
20-
// cache_folder_name: the folder name in under ./ModelCache/ to store model caches. This name is better
21-
// to be unique for each model for easier file management.
22-
//
19+
// Create an ONNX SessionOptions
2320
// If on macOS, will use CoreML as the backend.
2421
// Otherwise, use CPU to run the model.
2522
// TODO: add Cuda backend for Windows machine.
26-
Ort::Session create_session(const std::string& model_path, const std::string& cache_folder_name);
23+
//
24+
// model_cache_path: the path to store model caches. This path is better
25+
// to be unique for each model for easier file management.
26+
Ort::SessionOptions create_session_options(const std::string& model_cache_path);
27+
28+
29+
// Create an ONNX Session. It will also update the model cache on macOS if necessary.
30+
// model_cache_path: the path to store model caches. This path must be the same path
31+
// used in `create_session_options()` to construct the passed-in session options so.
32+
Ort::Session create_session(const Ort::Env& env, const Ort::SessionOptions& so,
33+
const std::string& model_path, const std::string& model_cache_path);
2734

2835
// Handy function to create an ONNX Runtime tensor view class from a vector-like `buffer` object holding
2936
// the tensor data and an array-like `shape` object that represents the dimension of the tensor.

0 commit comments

Comments
 (0)