2#ifndef RIVET_RivetONNXrt_HH
3#define RIVET_RivetONNXrt_HH
11#include "Rivet/Tools/RivetPaths.hh"
12#include "Rivet/Tools/Utils.hh"
13#include "onnxruntime/onnxruntime_cxx_api.h"
27 RivetONNXrt() =
delete;
30 RivetONNXrt(
const string& filename,
const string& runname =
"RivetONNXrt",
const int maxOrtThreads = 1) {
34 _env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, runname.c_str());
37 Ort::SessionOptions sessionopts;
43 if (envMaxOrtThreads == 0) {
46 const int used_threads =
min(maxOrtThreads, max_threads);
47 sessionopts.SetIntraOpNumThreads(used_threads);
48 MSG_DEBUG(
"Using " << used_threads <<
" ORT threads");
51 else if (envMaxOrtThreads >= 1) {
52 const int used_threads =
min(maxOrtThreads, envMaxOrtThreads);
53 MSG_DEBUG(
"Using " << used_threads <<
" ORT threads.");
54 sessionopts.SetIntraOpNumThreads(used_threads);
59 <<
" ORT threads, as forced by the negative RIVET_ORT_MAX_THREADS value.");
60 sessionopts.SetIntraOpNumThreads(abs(envMaxOrtThreads));
66 _session = std::make_unique<Ort::Session>(*_env, filename.c_str(), sessionopts);
68 catch (
const std::exception& e) {
69 MSG_ERROR(
"Failure loading onnx file: " << e.what());
82 template <
typename T =
float>
83 vector<vector<T>>
compute(
const vector<vector<T>>& inputs)
const {
86 if (inputs.size() != _inDims.size()) {
87 throw DataError(
"Expected " + to_string(_inDims.size()) +
" input nodes, " +
"received "
88 + to_string(inputs.size()));
92 for (
size_t i = 0; i < _outTypes.size(); ++i) {
93 if (_outTypes[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED)
94 throw DataError(
"Output node " + to_string(i) +
" (" +
string(_outNames[i])
95 +
") is not a tensor — use computeMaps() for Seq(Map) outputs");
99 vector<Ort::Value> ort_input;
100 ort_input.reserve(_inDims.size());
101 auto memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
102 for (
size_t i = 0; i < _inDims.size(); ++i) {
105 if (inputs[i].size() != (
size_t)_inDimsFlat[i]) {
106 throw DataError(
"Expected flattened dimension " + to_string(_inDimsFlat[i]) +
" for input node "
107 + to_string(i) +
", received " + to_string(inputs[i].size()));
111 _checkTypes(inputs[i].data(), i);
113 ort_input.emplace_back(Ort::Value::CreateTensor<T>(memory_info,
const_cast<T*
>(inputs[i].data()),
114 inputs[i].size(), _inDims[i].data(),
119 auto ort_output = _session->Run(Ort::RunOptions{
nullptr}, _inNames.data(), ort_input.data(),
120 ort_input.size(), _outNames.data(), _outNames.size());
123 vector<vector<T>> outputs;
124 outputs.resize(_outDims.size());
125 for (
size_t i = 0; i < _outDims.size(); ++i) {
126 T* floatarr = ort_output[i].GetTensorMutableData<T>();
127 outputs[i].assign(floatarr, floatarr + _outDimsFlat[i]);
134 template <
typename T =
float>
135 vector<T>
compute(
const vector<T>& inputs)
const {
136 if (_inDims.size() != 1 || _outDims.size() != 1) {
137 throw(
"This method assumes a single input/output node!");
139 vector<vector<T>> wrapped_inputs = {inputs};
140 vector<vector<T>> outputs =
compute(wrapped_inputs);
147 template <
typename K =
long,
typename V =
float>
148 vector<map<K, V>>
computeMaps(
const vector<vector<V>>& inputs)
const {
150 if (inputs.size() != _inDims.size()) {
151 throw DataError(
"Expected " + to_string(_inDims.size()) +
" input nodes, " +
"received "
152 + to_string(inputs.size()));
156 const bool has_seq_map = std::any_of(_outTypes.begin(), _outTypes.end(), [](
auto t) {
157 return t == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
159 if (!has_seq_map)
throw DataError(
"No Seq(Map) outputs found in this model — use compute() instead");
161 vector<Ort::Value> ort_input;
162 ort_input.reserve(_inDims.size());
163 auto memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
164 for (
size_t i = 0; i < _inDims.size(); ++i) {
165 if (inputs[i].size() != (
size_t)_inDimsFlat[i]) {
166 throw DataError(
"Expected flattened dimension " + to_string(_inDimsFlat[i]) +
" for input node "
167 + to_string(i) +
", received " + to_string(inputs[i].size()));
169 _checkTypes(inputs[i].data(), i);
170 ort_input.emplace_back(Ort::Value::CreateTensor<V>(memory_info,
const_cast<V*
>(inputs[i].data()),
171 inputs[i].size(), _inDims[i].data(),
175 auto ort_output = _session->Run(Ort::RunOptions{
nullptr}, _inNames.data(), ort_input.data(),
176 ort_input.size(), _outNames.data(), _outNames.size());
178 vector<map<K, V>> outputs(_outDims.size());
179 Ort::AllocatorWithDefaultOptions alloc;
180 for (
size_t i = 0; i < _outDims.size(); ++i) {
181 if (ort_output[i].IsTensor())
continue;
183 auto map_val = ort_output[i].GetValue(0, alloc);
184 auto keys_val = map_val.GetValue(0, alloc);
185 auto vals_val = map_val.GetValue(1, alloc);
186 const int64_t n = keys_val.GetTensorTypeAndShapeInfo().GetShape()[0];
187 const K* keys = keys_val.GetTensorMutableData<K>();
188 const float* vals = vals_val.GetTensorMutableData<
float>();
189 for (int64_t j = 0; j < n; ++j) outputs[i][keys[j]] = static_cast<V>(vals[j]);
196 template <
typename K =
long,
typename V =
float>
198 if (_inDims.size() != 1 || _outDims.size() != 1) {
199 throw(
"This method assumes a single input/output node!");
206 bool hasKey(
const std::string& key)
const {
207 Ort::AllocatorWithDefaultOptions allocator;
208 return (
bool)_metadata->LookupCustomMetadataMapAllocated(key.c_str(), allocator);
214 template <
typename T,
typename std::enable_if_t<!is_iterable_v<T> | is_c
string_v<T>>>
216 Ort::AllocatorWithDefaultOptions allocator;
217 Ort::AllocatedStringPtr res = _metadata->LookupCustomMetadataMapAllocated(key.c_str(), allocator);
219 throw(
"Key '" + key +
"' not found in network metadata!");
228 std::string
retrieve(
const std::string& key)
const {
229 Ort::AllocatorWithDefaultOptions allocator;
230 Ort::AllocatedStringPtr res = _metadata->LookupCustomMetadataMapAllocated(key.c_str(), allocator);
232 throw(
"Key '" + key +
"' not found in network metadata!");
238 template <
typename T>
241 vector<T> returnvec = {};
242 for (
const string& s : stringvec) {
249 template <
typename T>
250 vector<T>
retrieve(
const std::string& key,
const vector<T>& defaultreturn)
const {
255 return defaultreturn;
259 std::string
retrieve(
const std::string& key,
const std::string& defaultreturn)
const {
264 return defaultreturn;
270 template <
typename T,
typename std::enable_if_t<!is_iterable_v<T> | is_c
string_v<T>>>
271 T
retrieve(
const std::string& key,
const T& defaultreturn)
const {
276 return defaultreturn;
281 friend std::ostream&
operator<<(std::ostream& os,
const RivetONNXrt& rort) {
282 os <<
"RivetONNXrt Network Summary: \n";
283 for (
size_t i = 0; i < rort._inNames.size(); ++i) {
284 os <<
"- Input node " << i <<
" name: " << rort._inNames[i];
285 os <<
", dimensions: (";
286 for (
size_t j = 0; j < rort._inDims[i].size(); ++j) {
288 os << rort._inDims[i][j];
290 os <<
"), type (as ONNX enums): " << rort._inTypes[i] <<
"\n";
292 for (
size_t i = 0; i < rort._outNames.size(); ++i) {
293 os <<
"- Output node " << i <<
" name: " << rort._outNames[i];
294 os <<
", dimensions: (";
295 for (
size_t j = 0; j < rort._outDims[i].size(); ++j) {
297 os << rort._outDims[i][j];
299 os <<
"), type (as ONNX enums): (" << rort._outTypes[i] <<
"\n";
306 string logname =
"Rivet.RivetONNXrt." + _runName;
314 void getNetworkInfo() {
316 Ort::AllocatorWithDefaultOptions allocator;
319 _metadata = std::make_unique<Ort::ModelMetadata>(_session->GetModelMetadata());
322 const size_t num_input_nodes = _session->GetInputCount();
323 _inDimsFlat.reserve(num_input_nodes);
324 _inTypes.reserve(num_input_nodes);
325 _inDims.reserve(num_input_nodes);
326 _inNames.reserve(num_input_nodes);
327 _inNamesPtr.reserve(num_input_nodes);
328 for (
size_t i = 0; i < num_input_nodes; ++i) {
330 auto input_name = _session->GetInputNameAllocated(i, allocator);
331 _inNames.push_back(input_name.get());
332 _inNamesPtr.push_back(std::move(input_name));
335 auto in_type_info = _session->GetInputTypeInfo(i);
336 auto in_tensor_info = in_type_info.GetTensorTypeAndShapeInfo();
337 _inTypes.push_back(in_tensor_info.GetElementType());
338 _inDims.push_back(in_tensor_info.GetShape());
342 for (
auto& dims : _inDims) {
344 for (
auto& dim : dims) {
345 if (dim < 0) dim = abs(dim);
348 _inDimsFlat.push_back(n);
351 const size_t num_output_nodes = _session->GetOutputCount();
352 _outDimsFlat.reserve(num_output_nodes);
353 _outTypes.reserve(num_output_nodes);
354 _outDims.reserve(num_output_nodes);
355 _outNames.reserve(num_output_nodes);
356 _outNamesPtr.reserve(num_output_nodes);
357 for (
size_t i = 0; i < num_output_nodes; ++i) {
359 auto output_name = _session->GetOutputNameAllocated(i, allocator);
360 _outNames.push_back(output_name.get());
361 _outNamesPtr.push_back(std::move(output_name));
364 auto out_type_info = _session->GetOutputTypeInfo(i);
365 if (out_type_info.GetONNXType() == ONNX_TYPE_TENSOR) {
366 auto out_tensor_info = out_type_info.GetTensorTypeAndShapeInfo();
367 _outTypes.push_back(out_tensor_info.GetElementType());
368 _outDims.push_back(out_tensor_info.GetShape());
373 _outTypes.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED);
374 _outDims.push_back({-1});
379 for (
auto& dims : _outDims) {
381 for (
auto& dim : dims) {
382 if (dim < 0) dim = abs(dim);
385 _outDimsFlat.push_back(n);
391 void _checkTypes(
const float*,
size_t inode)
const {
392 if (_inTypes[inode] != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)
393 throw DataError(
"ONNX network provided wrong input type (float)");
396 void _checkTypes(
const double*,
size_t inode)
const {
397 if (_inTypes[inode] != ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE)
398 throw DataError(
"ONNX network provided wrong input type (double)");
404 std::string _runName;
407 std::unique_ptr<Ort::Env> _env;
410 std::unique_ptr<Ort::Session> _session;
413 std::unique_ptr<Ort::ModelMetadata> _metadata;
418 vector<vector<int64_t>> _inDims, _outDims;
421 vector<int64_t> _inDimsFlat, _outDimsFlat;
424 vector<ONNXTensorElementDataType> _inTypes, _outTypes;
427 vector<Ort::AllocatedStringPtr> _inNamesPtr, _outNamesPtr;
430 vector<const char*> _inNames, _outNames;
444 if (!path1.empty())
return path1;
445 throw Rivet::Error(
"Couldn't find an ONNX data file for '" + filename +
"' " +
"in the path "
459 const string& suffix =
"",
460 const string& extn =
"onnx",
461 const int maxOrtThreads = 1) {
462 const string fname = analysisname + (suffix.empty() ?
"" :
"-") + suffix +
"." + extn;
463 return make_unique<RivetONNXrt>(
getONNXFilePath(fname), analysisname +
"-onnxrt"s, maxOrtThreads);
Logging system for controlled & formatted writing to stdout.
Definition Logging.hh:10
static Log & getLog(const std::string &name)
Simple interface class to take care of basic ONNX networks.
Definition RivetONNXrt.hh:23
Log & getLog() const
Logger.
Definition RivetONNXrt.hh:305
RivetONNXrt(const string &filename, const string &runname="RivetONNXrt", const int maxOrtThreads=1)
Constructor.
Definition RivetONNXrt.hh:30
vector< T > compute(const vector< T > &inputs) const
Given a single-node input vector, populate and return the single-node output vector.
Definition RivetONNXrt.hh:135
T retrieve(const std::string &key, const T &defaultreturn) const
Definition RivetONNXrt.hh:271
std::string retrieve(const std::string &key) const
Template specialisation of retrieve for std::string.
Definition RivetONNXrt.hh:228
friend std::ostream & operator<<(std::ostream &os, const RivetONNXrt &rort)
Printing function for debugging.
Definition RivetONNXrt.hh:281
map< K, V > computeMap(const vector< V > &inputs) const
Single-node convenience overload: returns the map from a single Seq(Map(K,V)) output.
Definition RivetONNXrt.hh:197
vector< map< K, V > > computeMaps(const vector< vector< V > > &inputs) const
Definition RivetONNXrt.hh:148
vector< vector< T > > compute(const vector< vector< T > > &inputs) const
Definition RivetONNXrt.hh:83
vector< T > retrieve(const std::string &key, const vector< T > &defaultreturn) const
Overload of retrieve for vector<T>, with a default return.
Definition RivetONNXrt.hh:250
bool hasKey(const std::string &key) const
Method to check if key exists in network metatdata.
Definition RivetONNXrt.hh:206
T retrieve(const std::string &key) const
Definition RivetONNXrt.hh:215
vector< T > retrieve(const std::string &key) const
Overload of retrieve for vector<T>.
Definition RivetONNXrt.hh:239
#define MSG_DEBUG(x)
Debug messaging, not enabled by default, using MSG_LVL.
Definition Logging.hh:195
#define MSG_WARNING(x)
Warning messages for non-fatal bad things, using MSG_LVL.
Definition Logging.hh:200
#define MSG_ERROR(x)
Highest level messaging for serious problems, using MSG_LVL.
Definition Logging.hh:202
std::string findAnalysisDataFile(const std::string &filename, const std::vector< std::string > &pathprepend=std::vector< std::string >(), const std::vector< std::string > &pathappend=std::vector< std::string >())
Find the first file of the given name in the general data file search dirs.
std::string getRivetDataPath()
Get Rivet data install path.
T lexical_cast(const U &in)
Convert between any types via stringstream.
Definition Utils.hh:63
vector< string > split(const string &s, const string &sep)
Split a string on a specified separator string.
Definition Utils.hh:250
T getEnvParam(const std::string name, const T &fallback)
Get a parameter from a named environment variable, with automatic type conversion.
Definition Utils.hh:921
Definition LHCbCommon.hh:9
string getONNXFilePath(const string &filename)
Useful function for getting ONNX file paths.
Definition RivetONNXrt.hh:441
RivetONNXrtPtr getONNX(const string &analysisname, const string &suffix="", const string &extn="onnx", const int maxOrtThreads=1)
Definition RivetONNXrt.hh:458
std::enable_if_t< std::is_arithmetic_v< N1 > &&std::is_arithmetic_v< N2 >, signed_if_mixed_t< N1, N2 > > min(N1 a, N2 b)
Get the minimum of two numbers.
Definition MathUtils.hh:113
unique_ptr< RivetONNXrt > RivetONNXrtPtr
Typedef for a handle to an OONXrt object.
Definition RivetONNXrt.hh:435
std::string toString(const AnalysisInfo &ai)
String representation.
RivetONNXrt ONNXrt
Definition RivetONNXrt.hh:469
Error relating to provided data mismatching expectations.
Definition Exceptions.hh:89
Generic runtime Rivet error.
Definition Exceptions.hh:12