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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#![warn(missing_docs)]
#![cfg_attr(
feature = "model-fetching",
doc = r##"
Instead of loading a model from file using [`with_model_from_file()`](session/struct.SessionBuilder.html#method.with_model_from_file),
a model can be fetched directly from the [ONNX Model Zoo](https://github.com/onnx/models) using
[`with_model_downloaded()`](session/struct.SessionBuilder.html#method.with_model_downloaded) method
(requires the `model-fetching` feature).
```no_run
# use std::error::Error;
# use onnxruntime::{environment::Environment, download::vision::ImageClassification, LoggingLevel, GraphOptimizationLevel};
# fn main() -> Result<(), Box<dyn Error>> {
# let environment = Environment::builder()
# .with_name("test")
# .with_log_level(LoggingLevel::Verbose)
# .build()?;
let mut session = environment
.new_session_builder()?
.with_optimization_level(GraphOptimizationLevel::Basic)?
.with_number_threads(1)?
.with_model_downloaded(ImageClassification::SqueezeNet)?;
# Ok(())
# }
```
See [`AvailableOnnxModel`](download/enum.AvailableOnnxModel.html) for the different models available
to download.
"##
)]
use std::sync::{atomic::AtomicPtr, Arc, Mutex};
use lazy_static::lazy_static;
use onnxruntime_sys as sys;
pub mod download;
pub mod environment;
pub mod error;
mod memory;
pub mod session;
pub mod tensor;
pub use error::{OrtApiError, OrtError, Result};
lazy_static! {
static ref G_ORT_API: Arc<Mutex<AtomicPtr<sys::OrtApi>>> = {
let base: *const sys::OrtApiBase = unsafe { sys::OrtGetApiBase() };
assert_ne!(base, std::ptr::null());
let get_api: unsafe extern "C" fn(u32) -> *const onnxruntime_sys::OrtApi =
unsafe { (*base).GetApi.unwrap() };
let api: *const sys::OrtApi = unsafe { get_api(sys::ORT_API_VERSION) };
Arc::new(Mutex::new(AtomicPtr::new(api as *mut sys::OrtApi)))
};
}
fn g_ort() -> sys::OrtApi {
let mut api_ref = G_ORT_API
.lock()
.expect("Failed to acquire lock: another thread panicked?");
let api_ref_mut: &mut *mut sys::OrtApi = api_ref.get_mut();
let api_ptr_mut: *mut sys::OrtApi = *api_ref_mut;
assert_ne!(api_ptr_mut, std::ptr::null_mut());
unsafe { *api_ptr_mut }
}
fn char_p_to_string(raw: *const i8) -> Result<String> {
let c_string = unsafe { std::ffi::CString::from_raw(raw as *mut i8) };
match c_string.into_string() {
Ok(string) => Ok(string),
Err(e) => Err(OrtApiError::IntoStringError(e)),
}
.map_err(OrtError::StringConversion)
}
mod onnxruntime {
use std::ffi::CStr;
use tracing::{debug, error, info, span, trace, warn, Level};
#[derive(Debug)]
struct CodeLocation<'a> {
file: &'a str,
line_number: &'a str,
function: &'a str,
}
impl<'a> From<&'a str> for CodeLocation<'a> {
fn from(code_location: &'a str) -> Self {
let mut splitter = code_location.split(' ');
let file_and_line_number = splitter.next().unwrap_or("<unknown file:line>");
let function = splitter.next().unwrap_or("<unknown module>");
let mut file_and_line_number_splitter = file_and_line_number.split(':');
let file = file_and_line_number_splitter
.next()
.unwrap_or("<unknown file>");
let line_number = file_and_line_number_splitter
.next()
.unwrap_or("<unknown line number>");
CodeLocation {
file,
line_number,
function,
}
}
}
pub(crate) extern "C" fn custom_logger(
_params: *mut std::ffi::c_void,
severity: u32,
category: *const i8,
logid: *const i8,
code_location: *const i8,
message: *const i8,
) {
let log_level = match severity {
0 => Level::TRACE,
1 => Level::DEBUG,
2 => Level::INFO,
3 => Level::WARN,
_ => Level::ERROR,
};
assert_ne!(category, std::ptr::null());
let category = unsafe { CStr::from_ptr(category) };
assert_ne!(code_location, std::ptr::null());
let code_location = unsafe { CStr::from_ptr(code_location) }
.to_str()
.unwrap_or("unknown");
assert_ne!(message, std::ptr::null());
let message = unsafe { CStr::from_ptr(message) };
assert_ne!(logid, std::ptr::null());
let logid = unsafe { CStr::from_ptr(logid) };
let code_location: CodeLocation = code_location.into();
let span = span!(
Level::TRACE,
"onnxruntime",
category = category.to_str().unwrap_or("<unknown>"),
file = code_location.file,
line_number = code_location.line_number,
function = code_location.function,
logid = logid.to_str().unwrap_or("<unknown>"),
);
let _enter = span.enter();
match log_level {
Level::TRACE => trace!("{:?}", message),
Level::DEBUG => debug!("{:?}", message),
Level::INFO => info!("{:?}", message),
Level::WARN => warn!("{:?}", message),
Level::ERROR => error!("{:?}", message),
}
}
}
#[derive(Debug)]
#[repr(u32)]
pub enum LoggingLevel {
Verbose = sys::OrtLoggingLevel_ORT_LOGGING_LEVEL_VERBOSE,
Info = sys::OrtLoggingLevel_ORT_LOGGING_LEVEL_INFO,
Warning = sys::OrtLoggingLevel_ORT_LOGGING_LEVEL_WARNING,
Error = sys::OrtLoggingLevel_ORT_LOGGING_LEVEL_ERROR,
Fatal = sys::OrtLoggingLevel_ORT_LOGGING_LEVEL_FATAL,
}
#[derive(Debug)]
#[repr(u32)]
pub enum GraphOptimizationLevel {
DisableAll = sys::GraphOptimizationLevel_ORT_DISABLE_ALL,
Basic = sys::GraphOptimizationLevel_ORT_ENABLE_BASIC,
Extended = sys::GraphOptimizationLevel_ORT_ENABLE_EXTENDED,
All = sys::GraphOptimizationLevel_ORT_ENABLE_ALL,
}
#[derive(Debug)]
#[repr(u32)]
pub enum TensorElementDataType {
Float = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
Uint8 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8,
Int8 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8,
Uint16 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16,
Int16 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16,
Int32 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32,
Int64 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64,
Double = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE,
Uint32 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32,
Uint64 = sys::ONNXTensorElementDataType_ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64,
}
pub trait TypeToTensorElementDataType {
fn tensor_element_data_type() -> TensorElementDataType;
}
macro_rules! impl_type_trait {
($type_:ty, $variant:ident) => {
impl TypeToTensorElementDataType for $type_ {
fn tensor_element_data_type() -> TensorElementDataType {
TensorElementDataType::$variant
}
}
};
}
impl_type_trait!(f32, Float);
impl_type_trait!(u8, Uint8);
impl_type_trait!(i8, Int8);
impl_type_trait!(u16, Uint16);
impl_type_trait!(i16, Int16);
impl_type_trait!(i32, Int32);
impl_type_trait!(i64, Int64);
impl_type_trait!(f64, Double);
impl_type_trait!(u32, Uint32);
impl_type_trait!(u64, Uint64);
#[derive(Debug, Clone)]
#[repr(i32)]
pub enum AllocatorType {
Device = sys::OrtAllocatorType_OrtDeviceAllocator,
Arena = sys::OrtAllocatorType_OrtArenaAllocator,
}
#[derive(Debug, Clone)]
#[repr(i32)]
pub enum MemType {
Default = sys::OrtMemType_OrtMemTypeDefault,
}