Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
ml_model.cpp
Go to the documentation of this file.
1#include "PanoptesML.h"
2#include <onnxruntime/onnxruntime_cxx_api.h> // vcpkg installs the headers under include/onnxruntime
3#include <stdexcept>
4
6 Ort::Env Env{ ORT_LOGGING_LEVEL_WARNING, "PanoptesML" };
7 Ort::Session Session{ nullptr };
8 std::string InputName;
9 std::vector<std::string> OutputNames;
10 size_t ScoreOutput = 0; // index of the float tensor output the score is read from
11};
12
13static std::string Narrow(const std::wstring& Text)
14{
15 int length = WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), (int)Text.size(), NULL, 0, NULL, NULL);
16 std::string out(length, '\0');
17 WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), (int)Text.size(), out.data(), length, NULL, NULL);
18 return out;
19}
20
25static void QuietNodeDumps()
26{
27 for (const char* name : { "ORT_DEBUG_NODE_IO_DUMP_SHAPE_DATA", "ORT_DEBUG_NODE_IO_DUMP_NODE_PLACEMENT" }) {
28 if (GetEnvironmentVariableA(name, NULL, 0) == 0) {
29 SetEnvironmentVariableA(name, "0");
30 }
31 }
32}
33
34static Ort::SessionOptions MakeSessionOptions()
35{
36 Ort::SessionOptions options;
37 // One file is scored at a time and the container runs next to everything else on the
38 // machine, so keep the model from spreading across every core
39 options.SetIntraOpNumThreads(1);
40 options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
41 return options;
42}
43
44MlModel::MlModel(const std::wstring& ModelPath)
45 : m_impl((QuietNodeDumps(), std::make_unique<Impl>()))
46{
47 m_name = Narrow(ModelPath.substr(ModelPath.find_last_of(L"\\/") + 1));
48 m_impl->Session = Ort::Session(m_impl->Env, ModelPath.c_str(), MakeSessionOptions());
49 Inspect();
50}
51
52MlModel::MlModel(const void* Data, size_t Size, const std::string& Name)
53 : m_impl((QuietNodeDumps(), std::make_unique<Impl>())), m_name(Name)
54{
55 // ONNX Runtime copies what it needs; the caller may wipe Data afterwards
56 m_impl->Session = Ort::Session(m_impl->Env, Data, Size, MakeSessionOptions());
57 Inspect();
58}
59
60void MlModel::Inspect()
61{
62 Ort::AllocatorWithDefaultOptions allocator;
63 if (m_impl->Session.GetInputCount() != 1) {
64 throw std::runtime_error(m_name + " must have one input, the feature vector");
65 }
66 m_impl->InputName = m_impl->Session.GetInputNameAllocated(0, allocator).get();
67
68 // The input must be [N, FEATURE_COUNT] floats; N may be dynamic (-1). The shape info is a
69 // view into the TypeInfo, so the TypeInfo must outlive it: not a temporary
70 Ort::TypeInfo inputType = m_impl->Session.GetInputTypeInfo(0);
71 auto input = inputType.GetTensorTypeAndShapeInfo();
72 std::vector<int64_t> shape = input.GetShape();
73 if (input.GetElementType() != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT || shape.size() != 2 ||
74 (shape[1] != -1 && shape[1] != (int64_t)FEATURE_COUNT)) {
75 throw std::runtime_error(m_name + " must take a float tensor of shape [N, " +
76 std::to_string(FEATURE_COUNT) + "] (feature version " + std::to_string(PANO_ML_FEATURE_VERSION) + ")");
77 }
78
79 // Classifiers exported from scikit-learn output a label and then the probabilities; the
80 // score is the last value of the first float tensor output
81 bool found = false;
82 for (size_t i = 0; i < m_impl->Session.GetOutputCount(); i++) {
83 m_impl->OutputNames.push_back(m_impl->Session.GetOutputNameAllocated(i, allocator).get());
84 Ort::TypeInfo type = m_impl->Session.GetOutputTypeInfo(i);
85 if (!found && type.GetONNXType() == ONNX_TYPE_TENSOR &&
86 type.GetTensorTypeAndShapeInfo().GetElementType() == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) {
87 m_impl->ScoreOutput = i;
88 found = true;
89 }
90 }
91 if (!found) {
92 throw std::runtime_error(m_name + " has no float tensor output to read the score from "
93 "(export scikit-learn classifiers with zipmap disabled)");
94 }
95}
96
97MlModel::~MlModel() = default;
98
99float MlModel::Score(const std::vector<float>& Features)
100{
101 if (Features.size() != FEATURE_COUNT) {
102 throw std::runtime_error("expected " + std::to_string(FEATURE_COUNT) + " features, got " + std::to_string(Features.size()));
103 }
104
105 Ort::MemoryInfo memory = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
106 const int64_t shape[2] = { 1, (int64_t)FEATURE_COUNT };
107 Ort::Value input = Ort::Value::CreateTensor<float>(memory, const_cast<float*>(Features.data()),
108 Features.size(), shape, 2);
109
110 const char* inputName = m_impl->InputName.c_str();
111 const char* outputName = m_impl->OutputNames[m_impl->ScoreOutput].c_str();
112 std::vector<Ort::Value> outputs = m_impl->Session.Run(Ort::RunOptions{ nullptr }, &inputName, &input, 1, &outputName, 1);
113
114 auto info = outputs[0].GetTensorTypeAndShapeInfo();
115 size_t count = info.GetElementCount();
116 if (count == 0) {
117 throw std::runtime_error(m_name + " returned an empty score");
118 }
119 return outputs[0].GetTensorData<float>()[count - 1];
120}
121
122std::wstring ModuleDirectory()
123{
124 HMODULE module = NULL;
125 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
126 (LPCWSTR)&ModuleDirectory, &module);
127 WCHAR path[MAX_PATH];
128 DWORD length = GetModuleFileNameW(module, path, MAX_PATH);
129 std::wstring directory(path, length);
130 return directory.substr(0, directory.find_last_of(L'\\') + 1);
131}
std::wstring ModuleDirectory()
The folder this DLL was loaded from, with a trailing backslash.
Definition ml_model.cpp:122
#define PANO_ML_FEATURE_VERSION
Version of the feature layout below. A model is trained for one layout; change this whenever a featur...
Definition PanoptesML.h:23
@ FEATURE_COUNT
Definition PanoptesML.h:51
#define MAX_PATH
Definition callbacks.h:7
float Score(const std::vector< float > &Features)
Runs the model on one file's features. Returns the malicious probability.
Definition ml_model.cpp:99
MlModel(const std::wstring &ModelPath)
Loads the model. Throws Ort::Exception or std::runtime_error when it can't be loaded or doesn't take ...
Definition ml_model.cpp:44
const std::string & Name() const
Definition PanoptesML.h:87
std::wstring ModuleDirectory()
The folder this DLL was loaded from, with a trailing backslash.
Definition ml_model.cpp:122
Ort::Session Session
Definition ml_model.cpp:7
std::string InputName
Definition ml_model.cpp:8
size_t ScoreOutput
Definition ml_model.cpp:10
Ort::Env Env
Definition ml_model.cpp:6
std::vector< std::string > OutputNames
Definition ml_model.cpp:9