forked from xmba15/onnx_runtime_cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrtSessionHandler.cpp
More file actions
345 lines (290 loc) · 10.9 KB
/
OrtSessionHandler.cpp
File metadata and controls
345 lines (290 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* @file OrtSessionHandler.cpp
*
* @author btran
*
*/
#include <onnxruntime/core/session/onnxruntime_c_api.h>
#include <onnxruntime/core/session/onnxruntime_cxx_api.h>
#if ENABLE_TENSORRT
#include <onnxruntime/core/providers/tensorrt/tensorrt_provider_factory.h>
#endif
#include <ort_utility/ort_utility.hpp>
#include <algorithm>
#include <cassert>
#include <numeric>
#include <sstream>
namespace
{
std::string toString(const ONNXTensorElementDataType dataType)
{
switch (dataType) {
case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: {
return "float";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: {
return "uint8_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: {
return "int8_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16: {
return "uint16_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16: {
return "int16_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: {
return "int32_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: {
return "int64_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING: {
return "string";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: {
return "bool";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16: {
return "float16";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE: {
return "double";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: {
return "uint32_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: {
return "uint64_t";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64: {
return "complex with float32 real and imaginary components";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128: {
return "complex with float64 real and imaginary components";
}
case ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16: {
return "complex with float64 real and imaginary components";
}
default:
return "undefined";
}
}
} // namespace
namespace Ort
{
//-----------------------------------------------------------------------------//
// OrtSessionHandlerIml Definition
//-----------------------------------------------------------------------------//
class OrtSessionHandler::OrtSessionHandlerIml
{
public:
OrtSessionHandlerIml(const std::string& modelPath, //
const std::optional<size_t>& gpuIdx, //
const std::optional<std::vector<std::vector<int64_t>>>& inputShapes);
~OrtSessionHandlerIml();
std::vector<DataOutputType> operator()(const std::vector<float*>& inputData) const;
void updateInputShapes(const std::vector<std::vector<int64_t>>& inputShapes)
{
if (inputShapes.size() != m_numInputs) {
DEBUG_LOG("inputShapes must be of size: %d", m_numInputs);
return;
}
m_inputShapes = inputShapes;
for (int i = 0; i < m_numInputs; i++) {
const auto& curInputShape = m_inputShapes[i];
m_inputTensorSizes[i] =
std::accumulate(std::begin(curInputShape), std::end(curInputShape), 1, std::multiplies<int64_t>());
}
}
private:
void initSession();
void initModelInfo();
private:
std::string m_modelPath;
mutable Ort::Session m_session;
Ort::Env m_env;
Ort::AllocatorWithDefaultOptions m_ortAllocator;
std::optional<size_t> m_gpuIdx;
std::vector<std::vector<int64_t>> m_inputShapes;
std::vector<std::vector<int64_t>> m_outputShapes;
std::vector<int64_t> m_inputTensorSizes;
std::vector<int64_t> m_outputTensorSizes;
uint8_t m_numInputs;
uint8_t m_numOutputs;
std::vector<char*> m_inputNodeNames;
std::vector<char*> m_outputNodeNames;
bool m_inputShapesProvided = false;
};
//-----------------------------------------------------------------------------//
// OrtSessionHandler
//-----------------------------------------------------------------------------//
OrtSessionHandler::OrtSessionHandler(const std::string& modelPath, //
const std::optional<size_t>& gpuIdx, //
const std::optional<std::vector<std::vector<int64_t>>>& inputShapes)
: m_piml(std::make_unique<OrtSessionHandlerIml>(modelPath, //
gpuIdx, //
inputShapes))
{
}
OrtSessionHandler::~OrtSessionHandler() = default;
std::vector<OrtSessionHandler::DataOutputType>
OrtSessionHandler::operator()(const std::vector<float*>& inputImgData) const
{
return this->m_piml->operator()(inputImgData);
}
//-----------------------------------------------------------------------------//
// piml class implementation
//-----------------------------------------------------------------------------//
OrtSessionHandler::OrtSessionHandlerIml::OrtSessionHandlerIml(
const std::string& modelPath, //
const std::optional<size_t>& gpuIdx, //
const std::optional<std::vector<std::vector<int64_t>>>& inputShapes)
: m_modelPath(modelPath)
, m_session(nullptr)
, m_env(nullptr)
, m_ortAllocator()
, m_gpuIdx(gpuIdx)
, m_inputShapes()
, m_outputShapes()
, m_numInputs(0)
, m_numOutputs(0)
, m_inputNodeNames()
, m_outputNodeNames()
{
this->initSession();
if (inputShapes.has_value()) {
m_inputShapesProvided = true;
m_inputShapes = inputShapes.value();
}
this->initModelInfo();
}
OrtSessionHandler::OrtSessionHandlerIml::~OrtSessionHandlerIml()
{
for (auto& elem : this->m_inputNodeNames) {
free(elem);
elem = nullptr;
}
this->m_inputNodeNames.clear();
for (auto& elem : this->m_outputNodeNames) {
free(elem);
elem = nullptr;
}
this->m_outputNodeNames.clear();
}
void OrtSessionHandler::OrtSessionHandlerIml::initSession()
{
#if ENABLE_DEBUG
m_env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "test");
#else
m_env = Ort::Env(ORT_LOGGING_LEVEL_ERROR, "test");
#endif
Ort::SessionOptions sessionOptions;
sessionOptions.SetIntraOpNumThreads(1);
// tensorrt options can be customized into sessionOptions
// https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html
#if ENABLE_GPU
if (m_gpuIdx.has_value()) {
Ort::ThrowOnError(OrtSessionOptionsAppendExecutionProvider_CUDA(sessionOptions, m_gpuIdx.value()));
#if ENABLE_TENSORRT
Ort::ThrowOnError(OrtSessionOptionsAppendExecutionProvider_Tensorrt(sessionOptions, m_gpuIdx.value()));
#endif
}
#endif
sessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
m_session = Ort::Session(m_env, m_modelPath.c_str(), sessionOptions);
m_numInputs = m_session.GetInputCount();
DEBUG_LOG("Model number of inputs: %d\n", m_numInputs);
m_inputNodeNames.reserve(m_numInputs);
m_inputTensorSizes.reserve(m_numInputs);
m_numOutputs = m_session.GetOutputCount();
DEBUG_LOG("Model number of outputs: %d\n", m_numOutputs);
m_outputNodeNames.reserve(m_numOutputs);
m_outputTensorSizes.reserve(m_numOutputs);
}
void OrtSessionHandler::OrtSessionHandlerIml::initModelInfo()
{
for (int i = 0; i < m_numInputs; i++) {
if (!m_inputShapesProvided) {
Ort::TypeInfo typeInfo = m_session.GetInputTypeInfo(i);
auto tensorInfo = typeInfo.GetTensorTypeAndShapeInfo();
m_inputShapes.emplace_back(tensorInfo.GetShape());
}
const auto& curInputShape = m_inputShapes[i];
m_inputTensorSizes.emplace_back(
std::accumulate(std::begin(curInputShape), std::end(curInputShape), 1, std::multiplies<int64_t>()));
#if ORT_API_VERSION > 12
m_inputNodeNames.emplace_back(strdup(m_session.GetInputNameAllocated(i, m_ortAllocator).get()));
#else
char* inputName = m_session.GetInputName(i, m_ortAllocator);
m_inputNodeNames.emplace_back(strdup(inputName));
m_ortAllocator.Free(inputName);
#endif
}
{
#if ENABLE_DEBUG
std::stringstream ssInputs;
ssInputs << "Model input shapes: ";
ssInputs << m_inputShapes << std::endl;
ssInputs << "Model input node names: ";
ssInputs << m_inputNodeNames << std::endl;
DEBUG_LOG("%s\n", ssInputs.str().c_str());
#endif
}
for (int i = 0; i < m_numOutputs; ++i) {
Ort::TypeInfo typeInfo = m_session.GetOutputTypeInfo(i);
auto tensorInfo = typeInfo.GetTensorTypeAndShapeInfo();
m_outputShapes.emplace_back(tensorInfo.GetShape());
#if ORT_API_VERSION > 12
m_outputNodeNames.emplace_back(strdup(m_session.GetOutputNameAllocated(i, m_ortAllocator).get()));
#else
char* outputName = m_session.GetOutputName(i, m_ortAllocator);
m_outputNodeNames.emplace_back(strdup(outputName));
m_ortAllocator.Free(outputName);
#endif
}
{
#if ENABLE_DEBUG
std::stringstream ssOutputs;
ssOutputs << "Model output shapes: ";
ssOutputs << m_outputShapes << std::endl;
ssOutputs << "Model output node names: ";
ssOutputs << m_outputNodeNames << std::endl;
DEBUG_LOG("%s\n", ssOutputs.str().c_str());
#endif
}
}
std::vector<OrtSessionHandler::DataOutputType>
OrtSessionHandler::OrtSessionHandlerIml::operator()(const std::vector<float*>& inputData) const
{
if (m_numInputs != inputData.size()) {
DEBUG_LOG("m_numInputs:%d, input size:%ld", m_numInputs, inputData.size());
throw std::runtime_error("Mismatch size of input data");
}
Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
std::vector<Ort::Value> inputTensors;
inputTensors.reserve(m_numInputs);
for (int i = 0; i < m_numInputs; ++i) {
inputTensors.emplace_back(std::move(
Ort::Value::CreateTensor<float>(memoryInfo, const_cast<float*>(inputData[i]), m_inputTensorSizes[i],
m_inputShapes[i].data(), m_inputShapes[i].size())));
}
auto outputTensors = m_session.Run(Ort::RunOptions{nullptr}, m_inputNodeNames.data(), inputTensors.data(),
m_numInputs, m_outputNodeNames.data(), m_numOutputs);
assert(outputTensors.size() == m_numOutputs);
std::vector<DataOutputType> outputData;
outputData.reserve(m_numOutputs);
int count = 1;
for (auto& elem : outputTensors) {
DEBUG_LOG("type of input %d: %s", count++, toString(elem.GetTensorTypeAndShapeInfo().GetElementType()).c_str());
outputData.emplace_back(
std::make_pair(std::move(elem.GetTensorMutableData<float>()), elem.GetTensorTypeAndShapeInfo().GetShape()));
}
return outputData;
}
void OrtSessionHandler::updateInputShapes(const std::vector<std::vector<int64_t>>& inputShapes)
{
m_piml->updateInputShapes(inputShapes);
}
} // namespace Ort