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  session_ = std::make_unique<Session>(env_, model_path.c_str(), defaultSessionOptions());
31  }
32  AllocatorWithDefaultOptions allocator;
33 
34  // get input names and shapes
35  size_t num_input_nodes = session_->GetInputCount();
36  input_node_strings_.resize(num_input_nodes);
37  input_node_names_.resize(num_input_nodes);
38  input_node_dims_.clear();
39 
40  for (size_t i = 0; i < num_input_nodes; i++) {
41  // get input node names
42  std::string input_name(session_->GetInputName(i, allocator));
43  input_node_strings_[i] = input_name;
45 
46  // get input shapes
47  auto type_info = session_->GetInputTypeInfo(i);
48  auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
49  size_t num_dims = tensor_info.GetDimensionsCount();
50  input_node_dims_[input_name].resize(num_dims);
51  tensor_info.GetDimensions(input_node_dims_[input_name].data(), num_dims);
52  }
53 
54  size_t num_output_nodes = session_->GetOutputCount();
55  output_node_strings_.resize(num_output_nodes);
56  output_node_names_.resize(num_output_nodes);
57  output_node_dims_.clear();
58 
59  for (size_t i = 0; i < num_output_nodes; i++) {
60  // get output node names
61  std::string output_name(session_->GetOutputName(i, allocator));
62  output_node_strings_[i] = output_name;
64 
65  // get output node types
66  auto type_info = session_->GetOutputTypeInfo(i);
67  auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
68  size_t num_dims = tensor_info.GetDimensionsCount();
69  output_node_dims_[output_name].resize(num_dims);
70  tensor_info.GetDimensions(output_node_dims_[output_name].data(), num_dims);
71 
72  // the 0th dim depends on the batch size
73  output_node_dims_[output_name].at(0) = -1;
74  }
75  }
76 
78 
80  SessionOptions sess_opts;
81  sess_opts.SetIntraOpNumThreads(1);
82  if (backend == Backend::cuda) {
83  // https://www.onnxruntime.ai/docs/reference/execution-providers/CUDA-ExecutionProvider.html
84  OrtCUDAProviderOptions options;
85  sess_opts.AppendExecutionProvider_CUDA(options);
86  }
87  return sess_opts;
88  }
89 
90  FloatArrays ONNXRuntime::run(const std::vector<std::string>& input_names,
91  FloatArrays& input_values,
92  const std::vector<std::vector<int64_t>>& input_shapes,
93  const std::vector<std::string>& output_names,
94  int64_t batch_size) const {
95  assert(input_names.size() == input_values.size());
96  assert(input_shapes.empty() || input_names.size() == input_shapes.size());
97  assert(batch_size > 0);
98 
99  // create input tensor objects from data values
100  std::vector<Value> input_tensors;
101  auto memory_info = MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
102  for (const auto& name : input_node_strings_) {
103  auto iter = std::find(input_names.begin(), input_names.end(), name);
104  if (iter == input_names.end()) {
105  throw cms::Exception("RuntimeError") << "Input " << name << " is not provided!";
106  }
107  auto input_pos = iter - input_names.begin();
108  auto value = input_values.begin() + input_pos;
109  std::vector<int64_t> input_dims;
110  if (input_shapes.empty()) {
111  input_dims = input_node_dims_.at(name);
112  input_dims[0] = batch_size;
113  } else {
114  input_dims = input_shapes[input_pos];
115  // rely on the given input_shapes to set the batch size
116  if (input_dims[0] != batch_size) {
117  throw cms::Exception("RuntimeError") << "The first element of `input_shapes` (" << input_dims[0]
118  << ") does not match the given `batch_size` (" << batch_size << ")";
119  }
120  }
121  auto expected_len = std::accumulate(input_dims.begin(), input_dims.end(), 1, std::multiplies<int64_t>());
122  if (expected_len != (int64_t)value->size()) {
123  throw cms::Exception("RuntimeError")
124  << "Input array " << name << " has a wrong size of " << value->size() << ", expected " << expected_len;
125  }
126  auto input_tensor =
127  Value::CreateTensor<float>(memory_info, value->data(), value->size(), input_dims.data(), input_dims.size());
128  assert(input_tensor.IsTensor());
129  input_tensors.emplace_back(std::move(input_tensor));
130  }
131 
132  // set output node names; will get all outputs if `output_names` is not provided
133  std::vector<const char*> run_output_node_names;
134  if (output_names.empty()) {
135  run_output_node_names = output_node_names_;
136  } else {
137  for (const auto& name : output_names) {
138  run_output_node_names.push_back(name.c_str());
139  }
140  }
141 
142  // run
143  auto output_tensors = session_->Run(RunOptions{nullptr},
144  input_node_names_.data(),
145  input_tensors.data(),
146  input_tensors.size(),
147  run_output_node_names.data(),
148  run_output_node_names.size());
149 
150  // convert output to floats
152  for (auto& output_tensor : output_tensors) {
153  assert(output_tensor.IsTensor());
154 
155  // get output shape
156  auto tensor_info = output_tensor.GetTensorTypeAndShapeInfo();
157  auto length = tensor_info.GetElementCount();
158 
159  auto floatarr = output_tensor.GetTensorMutableData<float>();
160  outputs.emplace_back(floatarr, floatarr + length);
161  }
162  assert(outputs.size() == run_output_node_names.size());
163 
164  return outputs;
165  }
166 
167  const std::vector<std::string>& ONNXRuntime::getOutputNames() const {
168  if (session_) {
169  return output_node_strings_;
170  } else {
171  throw cms::Exception("RuntimeError") << "Needs to call createSession() first before getting the output names!";
172  }
173  }
174 
175  const std::vector<int64_t>& ONNXRuntime::getOutputShape(const std::string& output_name) const {
176  auto iter = output_node_dims_.find(output_name);
177  if (iter == output_node_dims_.end()) {
178  throw cms::Exception("RuntimeError") << "Output name " << output_name << " is invalid!";
179  } else {
180  return iter->second;
181  }
182  }
183 
184 } /* namespace cms::Ort */
std::unique_ptr<::Ort::Session > session_
Definition: ONNXRuntime.h:62
std::map< std::string, std::vector< int64_t > > input_node_dims_
Definition: ONNXRuntime.h:66
::Ort::SessionOptions defaultSessionOptions(Backend backend=Backend::cpu)
Definition: ONNXRuntime.cc:79
std::map< std::string, std::vector< int64_t > > output_node_dims_
Definition: ONNXRuntime.h:70
static const ::Ort::Env env_
Definition: ONNXRuntime.h:61
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
std::vector< std::vector< float > > FloatArrays
Definition: ONNXRuntime.h:23
assert(be >=bs)
const std::vector< std::string > & getOutputNames() const
Definition: ONNXRuntime.cc:167
ONNXRuntime(const std::string &model_path, const ::Ort::SessionOptions *session_options=nullptr)
Definition: value.py:1
const std::vector< int64_t > & getOutputShape(const std::string &output_name) const
Definition: ONNXRuntime.cc:175
std::vector< const char * > output_node_names_
Definition: ONNXRuntime.h:69
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:79
std::vector< std::string > input_node_strings_
Definition: ONNXRuntime.h:64
std::vector< const char * > input_node_names_
Definition: ONNXRuntime.h:65
def move(src, dest)
Definition: eostools.py:511
std::vector< std::string > output_node_strings_
Definition: ONNXRuntime.h:68
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:90