CMS 3D CMS Logo

ONNXRuntime.cc
Go to the documentation of this file.
1 /*
2  * ONNXRuntime.cc
3  *
4  * Created on: Jun 28, 2019
5  * Author: hqu
6  */
7 
9 
12 #include <algorithm>
13 #include <cassert>
14 #include <functional>
15 #include <iostream>
16 #include <memory>
17 #include <numeric>
18 
19 namespace cms::Ort {
20 
21  using namespace ::Ort;
22 
23  const Env ONNXRuntime::env_(ORT_LOGGING_LEVEL_ERROR, "");
24 
25  ONNXRuntime::ONNXRuntime(const std::string& model_path, const SessionOptions* session_options) {
26  // create session
27  if (session_options) {
28  session_ = std::make_unique<Session>(env_, model_path.c_str(), *session_options);
29  } else {
30  SessionOptions sess_opts;
31  sess_opts.SetIntraOpNumThreads(1);
32  session_ = std::make_unique<Session>(env_, model_path.c_str(), sess_opts);
33  }
34  AllocatorWithDefaultOptions allocator;
35 
36  // get input names and shapes
37  size_t num_input_nodes = session_->GetInputCount();
38  input_node_strings_.resize(num_input_nodes);
39  input_node_names_.resize(num_input_nodes);
40  input_node_dims_.clear();
41 
42  for (size_t i = 0; i < num_input_nodes; i++) {
43  // get input node names
44  std::string input_name(session_->GetInputName(i, allocator));
45  input_node_strings_[i] = input_name;
47 
48  // get input shapes
49  auto type_info = session_->GetInputTypeInfo(i);
50  auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
51  size_t num_dims = tensor_info.GetDimensionsCount();
52  input_node_dims_[input_name].resize(num_dims);
53  tensor_info.GetDimensions(input_node_dims_[input_name].data(), num_dims);
54  }
55 
56  size_t num_output_nodes = session_->GetOutputCount();
57  output_node_strings_.resize(num_output_nodes);
58  output_node_names_.resize(num_output_nodes);
59  output_node_dims_.clear();
60 
61  for (size_t i = 0; i < num_output_nodes; i++) {
62  // get output node names
63  std::string output_name(session_->GetOutputName(i, allocator));
64  output_node_strings_[i] = output_name;
66 
67  // get output node types
68  auto type_info = session_->GetOutputTypeInfo(i);
69  auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
70  size_t num_dims = tensor_info.GetDimensionsCount();
71  output_node_dims_[output_name].resize(num_dims);
72  tensor_info.GetDimensions(output_node_dims_[output_name].data(), num_dims);
73 
74  // the 0th dim depends on the batch size
75  output_node_dims_[output_name].at(0) = -1;
76  }
77  }
78 
80 
81  FloatArrays ONNXRuntime::run(const std::vector<std::string>& input_names,
82  FloatArrays& input_values,
83  const std::vector<std::vector<int64_t>>& input_shapes,
84  const std::vector<std::string>& output_names,
85  int64_t batch_size) const {
86  assert(input_names.size() == input_values.size());
87  assert(input_shapes.empty() || input_names.size() == input_shapes.size());
88  assert(batch_size > 0);
89 
90  // create input tensor objects from data values
91  std::vector<Value> input_tensors;
92  auto memory_info = MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
93  for (const auto& name : input_node_strings_) {
94  auto iter = std::find(input_names.begin(), input_names.end(), name);
95  if (iter == input_names.end()) {
96  throw cms::Exception("RuntimeError") << "Input " << name << " is not provided!";
97  }
98  auto input_pos = iter - input_names.begin();
99  auto value = input_values.begin() + input_pos;
100  std::vector<int64_t> input_dims;
101  if (input_shapes.empty()) {
102  input_dims = input_node_dims_.at(name);
103  input_dims[0] = batch_size;
104  } else {
105  input_dims = input_shapes[input_pos];
106  // rely on the given input_shapes to set the batch size
107  }
108  auto expected_len = std::accumulate(input_dims.begin(), input_dims.end(), 1, std::multiplies<int64_t>());
109  if (expected_len != (int64_t)value->size()) {
110  throw cms::Exception("RuntimeError")
111  << "Input array " << name << " has a wrong size of " << value->size() << ", expected " << expected_len;
112  }
113  auto input_tensor =
114  Value::CreateTensor<float>(memory_info, value->data(), value->size(), input_dims.data(), input_dims.size());
115  assert(input_tensor.IsTensor());
116  input_tensors.emplace_back(std::move(input_tensor));
117  }
118 
119  // set output node names; will get all outputs if `output_names` is not provided
120  std::vector<const char*> run_output_node_names;
121  if (output_names.empty()) {
122  run_output_node_names = output_node_names_;
123  } else {
124  for (const auto& name : output_names) {
125  run_output_node_names.push_back(name.c_str());
126  }
127  }
128 
129  // run
130  auto output_tensors = session_->Run(RunOptions{nullptr},
131  input_node_names_.data(),
132  input_tensors.data(),
133  input_tensors.size(),
134  run_output_node_names.data(),
135  run_output_node_names.size());
136 
137  // convert output to floats
139  for (auto& output_tensor : output_tensors) {
140  assert(output_tensor.IsTensor());
141 
142  // get output shape
143  auto tensor_info = output_tensor.GetTensorTypeAndShapeInfo();
144  auto length = tensor_info.GetElementCount();
145 
146  auto floatarr = output_tensor.GetTensorMutableData<float>();
147  outputs.emplace_back(floatarr, floatarr + length);
148  }
149  assert(outputs.size() == run_output_node_names.size());
150 
151  return outputs;
152  }
153 
154  const std::vector<std::string>& ONNXRuntime::getOutputNames() const {
155  if (session_) {
156  return output_node_strings_;
157  } else {
158  throw cms::Exception("RuntimeError") << "Needs to call createSession() first before getting the output names!";
159  }
160  }
161 
162  const std::vector<int64_t>& ONNXRuntime::getOutputShape(const std::string& output_name) const {
163  auto iter = output_node_dims_.find(output_name);
164  if (iter == output_node_dims_.end()) {
165  throw cms::Exception("RuntimeError") << "Output name " << output_name << " is invalid!";
166  } else {
167  return iter->second;
168  }
169  }
170 
171 } /* namespace cms::Ort */
mps_fire.i
i
Definition: mps_fire.py:428
cms::Ort::ONNXRuntime::session_
std::unique_ptr<::Ort::Session > session_
Definition: ONNXRuntime.h:55
PatBasicFWLiteJetAnalyzer_Selector_cfg.outputs
outputs
Definition: PatBasicFWLiteJetAnalyzer_Selector_cfg.py:48
cms::Ort::ONNXRuntime::env_
static const ::Ort::Env env_
Definition: ONNXRuntime.h:54
cms::cuda::assert
assert(be >=bs)
cms::Ort::ONNXRuntime::ONNXRuntime
ONNXRuntime(const std::string &model_path, const ::Ort::SessionOptions *session_options=nullptr)
spr::find
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
cms::Ort::ONNXRuntime::getOutputNames
const std::vector< std::string > & getOutputNames() const
Definition: ONNXRuntime.cc:154
ONNXRuntime.h
cms::Ort
Definition: ONNXRuntime.h:21
cms::Ort::ONNXRuntime::input_node_strings_
std::vector< std::string > input_node_strings_
Definition: ONNXRuntime.h:57
cms::Ort::ONNXRuntime::input_node_names_
std::vector< const char * > input_node_names_
Definition: ONNXRuntime.h:58
pfDeepBoostedJet_cff.model_path
model_path
Definition: pfDeepBoostedJet_cff.py:13
cms::Ort::ONNXRuntime::output_node_strings_
std::vector< std::string > output_node_strings_
Definition: ONNXRuntime.h:61
cms::Ort::ONNXRuntime::input_node_dims_
std::map< std::string, std::vector< int64_t > > input_node_dims_
Definition: ONNXRuntime.h:59
cms::Ort::ONNXRuntime::run
FloatArrays run(const std::vector< std::string > &input_names, FloatArrays &input_values, const std::vector< std::vector< int64_t >> &input_shapes={}, const std::vector< std::string > &output_names={}, int64_t batch_size=1) const
Definition: ONNXRuntime.cc:81
pfDeepBoostedJetPreprocessParams_cfi.input_names
input_names
Definition: pfDeepBoostedJetPreprocessParams_cfi.py:4
thread_safety_macros.h
value
Definition: value.py:1
trackerHitRTTI::vector
Definition: trackerHitRTTI.h:21
AlCaHLTBitMon_QueryRunRegistry.string
string string
Definition: AlCaHLTBitMon_QueryRunRegistry.py:256
cms::Ort::ONNXRuntime::getOutputShape
const std::vector< int64_t > & getOutputShape(const std::string &output_name) const
Definition: ONNXRuntime.cc:162
cms::Ort::FloatArrays
std::vector< std::vector< float > > FloatArrays
Definition: ONNXRuntime.h:23
eostools.move
def move(src, dest)
Definition: eostools.py:511
Exception
Definition: hltDiff.cc:245
Skims_PA_cff.name
name
Definition: Skims_PA_cff.py:17
Exception.h
data
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:79
cms::Ort::ONNXRuntime::output_node_names_
std::vector< const char * > output_node_names_
Definition: ONNXRuntime.h:62
cms::Ort::ONNXRuntime::output_node_dims_
std::map< std::string, std::vector< int64_t > > output_node_dims_
Definition: ONNXRuntime.h:63
cms::Ort::ONNXRuntime::~ONNXRuntime
~ONNXRuntime()
Definition: ONNXRuntime.cc:79