-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.cpp
More file actions
241 lines (200 loc) · 8.13 KB
/
Copy pathengine.cpp
File metadata and controls
241 lines (200 loc) · 8.13 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
#include "bai/engine.hpp"
#include <onnxruntime_cxx_api.h>
#include <algorithm>
#include <cstring>
#include <iostream>
namespace bai {
BaiEngine::BaiEngine()
: env_(nullptr), session_(nullptr), memory_info_(nullptr) {
}
BaiEngine::~BaiEngine() {
// RAII cleanup - unique_ptr handles deallocation
}
BaiEngine::BaiEngine(BaiEngine&& other) noexcept
: env_(std::move(other.env_)),
session_(std::move(other.session_)),
memory_info_(std::move(other.memory_info_)),
config_(std::move(other.config_)),
input_ids_buffer_(std::move(other.input_ids_buffer_)),
attention_mask_buffer_(std::move(other.attention_mask_buffer_)),
input_names_(std::move(other.input_names_)),
output_names_(std::move(other.output_names_)) {
}
BaiEngine& BaiEngine::operator=(BaiEngine&& other) noexcept {
if (this != &other) {
env_ = std::move(other.env_);
session_ = std::move(other.session_);
memory_info_ = std::move(other.memory_info_);
config_ = std::move(other.config_);
input_ids_buffer_ = std::move(other.input_ids_buffer_);
attention_mask_buffer_ = std::move(other.attention_mask_buffer_);
input_names_ = std::move(other.input_names_);
output_names_ = std::move(other.output_names_);
}
return *this;
}
std::expected<void, std::string> BaiEngine::initialize(
const EngineConfig& config) {
try {
if (config.max_seq_length != kModelSequenceLength) {
return std::unexpected(
"max_seq_length must be " + std::to_string(kModelSequenceLength)
);
}
if (config.num_threads <= 0) {
return std::unexpected("num_threads must be positive");
}
config_ = config;
// Initialize ONNX Runtime environment
env_ = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "bai_engine");
// Configure session options
auto session_options = std::make_unique<Ort::SessionOptions>();
session_options->SetIntraOpNumThreads(config.num_threads);
session_options->SetGraphOptimizationLevel(
static_cast<GraphOptimizationLevel>(config.graph_optimization_level)
);
// Enable GPU if requested
if (config.use_gpu) {
#ifdef ENABLE_CUDA
OrtCUDAProviderOptions cuda_options{};
cuda_options.device_id = config.device_id;
session_options->AppendExecutionProvider_CUDA(cuda_options);
#endif
} else {
// CPU is the default provider in the ONNX Runtime session.
}
// Create ONNX Runtime session
const wchar_t* model_path_w = nullptr;
#ifdef _WIN32
// Convert model path to wide string on Windows
std::wstring model_path_wide(config.model_path.begin(), config.model_path.end());
model_path_w = model_path_wide.c_str();
session_ = std::make_unique<Ort::Session>(
*env_, model_path_w, *session_options
);
#else
// Use char* directly on Unix-like systems
session_ = std::make_unique<Ort::Session>(
*env_, config.model_path.c_str(), *session_options
);
#endif
// Create memory info for CPU
memory_info_ = std::make_unique<Ort::MemoryInfo>(
Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault)
);
// Pre-allocate input/output buffers
input_ids_buffer_.resize(config.max_seq_length);
attention_mask_buffer_.resize(config.max_seq_length);
// Cache input node names
input_names_.clear();
input_names_.push_back("input_ids");
input_names_.push_back("attention_mask");
// Cache output node names
output_names_.clear();
output_names_.push_back("logits_category");
output_names_.push_back("logits_otp");
output_names_.push_back("confidence");
return {};
} catch (const Ort::Exception& e) {
return std::unexpected(
std::string("ONNX Runtime error: ") + e.what()
);
} catch (const std::exception& e) {
return std::unexpected(
std::string("Initialization error: ") + e.what()
);
}
}
std::string BaiEngine::validate_inputs(
std::span<const int64_t> input_ids,
std::span<const int64_t> attention_mask) const {
if (input_ids.empty()) {
return "input_ids cannot be empty";
}
if (input_ids.size() != attention_mask.size()) {
return "input_ids and attention_mask must have same length";
}
if (input_ids.size() > config_.max_seq_length) {
return "Sequence length exceeds max_seq_length";
}
return ""; // Empty string = valid
}
std::expected<InferenceResult, std::string> BaiEngine::infer(
std::span<const int64_t> input_ids,
std::span<const int64_t> attention_mask) {
if (!is_initialized()) {
return std::unexpected("Engine not initialized");
}
// Validate inputs (non-critical path)
std::string validation_error = validate_inputs(input_ids, attention_mask);
if (!validation_error.empty()) {
return std::unexpected(validation_error);
}
std::lock_guard lock(inference_mutex_);
try {
// Zero-allocation path: copy into pre-allocated buffers
const size_t seq_len = input_ids.size();
// Zero-initialize buffers (padding with zeros)
std::fill(input_ids_buffer_.begin(), input_ids_buffer_.end(), 0);
std::fill(attention_mask_buffer_.begin(), attention_mask_buffer_.end(), 0);
// Copy actual data
std::copy(input_ids.begin(), input_ids.end(), input_ids_buffer_.begin());
std::copy(attention_mask.begin(), attention_mask.end(),
attention_mask_buffer_.begin());
// Create input tensors from pre-allocated buffers
std::vector<int64_t> input_shape{1, static_cast<int64_t>(config_.max_seq_length)};
auto input_ids_tensor = Ort::Value::CreateTensor<int64_t>(
static_cast<const OrtMemoryInfo*>(*memory_info_),
input_ids_buffer_.data(),
input_ids_buffer_.size(),
input_shape.data(),
input_shape.size()
);
auto attention_mask_tensor = Ort::Value::CreateTensor<int64_t>(
static_cast<const OrtMemoryInfo*>(*memory_info_),
attention_mask_buffer_.data(),
attention_mask_buffer_.size(),
input_shape.data(),
input_shape.size()
);
// Prepare input tensors
std::vector<Ort::Value> input_tensors;
input_tensors.emplace_back(std::move(input_ids_tensor));
input_tensors.emplace_back(std::move(attention_mask_tensor));
// Run inference
auto output_tensors = session_->Run(
Ort::RunOptions{nullptr},
input_names_.data(),
input_tensors.data(),
input_tensors.size(),
output_names_.data(),
output_names_.size()
);
if (output_tensors.size() != 3) {
return std::unexpected(
"Expected 3 outputs, got " + std::to_string(output_tensors.size())
);
}
// Extract results
InferenceResult result{};
// Extract category logits (batch_size=1, num_categories=5)
float* category_data = output_tensors[0].GetTensorMutableData<float>();
std::copy(category_data, category_data + 5, result.category_logits.begin());
// Extract OTP logit (batch_size=1, 1)
float* otp_data = output_tensors[1].GetTensorMutableData<float>();
result.otp_logit = otp_data[0];
// Extract confidence (batch_size=1, 1)
float* confidence_data = output_tensors[2].GetTensorMutableData<float>();
result.confidence = confidence_data[0];
return result;
} catch (const Ort::Exception& e) {
return std::unexpected(
std::string("ONNX Runtime inference error: ") + e.what()
);
} catch (const std::exception& e) {
return std::unexpected(
std::string("Inference error: ") + e.what()
);
}
}
} // namespace bai