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
use crate::{ffi, Error, Tensor, TensorDescriptor, TensorMut};
use bitflags::bitflags;
use std::{
convert::TryInto,
ffi::CString,
fmt::{self, Debug, Formatter},
mem::MaybeUninit,
ptr::NonNull,
};
pub struct InferenceContext {
ctx: NonNull<ffi::RuneCoralContext>,
}
impl InferenceContext {
pub(crate) unsafe fn new(ctx: NonNull<ffi::RuneCoralContext>) -> Self {
InferenceContext { ctx }
}
pub fn infer(
&mut self,
inputs: &[Tensor<'_>],
outputs: &mut [TensorMut<'_>],
) -> Result<(), InferError> {
unsafe {
let inputs: Vec<_> = inputs.iter().map(|t| t.as_coral_tensor()).collect();
let mut outputs: Vec<_> = outputs.iter_mut().map(|t| t.as_coral_tensor()).collect();
let ret = ffi::infer(
self.ctx.as_ptr(),
inputs.as_ptr() as *mut _,
inputs.len() as ffi::size_t,
outputs.as_mut_ptr(),
outputs.len() as ffi::size_t,
);
check_inference_error(ret)
}
}
pub fn create_context(
mimetype: &str,
model: &[u8],
acceleration_backend: AccelerationBackend,
) -> Result<InferenceContext, Error> {
let mimetype = CString::new(mimetype)?;
let mut inference_context = MaybeUninit::uninit();
unsafe {
let ret = ffi::create_inference_context(
mimetype.as_ptr(),
model.as_ptr().cast(),
model.len() as ffi::size_t,
(acceleration_backend.bits() as i32).try_into().unwrap(),
inference_context.as_mut_ptr(),
);
check_load_result(ret)?;
let inference_context = inference_context.assume_init();
Ok(InferenceContext::new(
NonNull::new(inference_context).expect("Should be initialized"),
))
}
}
pub fn opcount(&self) -> u64 {
unsafe { ffi::inference_opcount(self.ctx.as_ptr()).into() }
}
pub fn inputs(&self) -> impl Iterator<Item = TensorDescriptor<'_>> + '_ {
unsafe {
let mut inputs = MaybeUninit::uninit();
let len = ffi::inference_inputs(self.ctx.as_ptr(), inputs.as_mut_ptr());
descriptors(inputs.assume_init(), len.into())
}
}
pub fn outputs(&self) -> impl Iterator<Item = TensorDescriptor<'_>> + '_ {
unsafe {
let mut outputs = MaybeUninit::uninit();
let len = ffi::inference_outputs(self.ctx.as_ptr(), outputs.as_mut_ptr());
descriptors(outputs.assume_init(), len.into())
}
}
}
unsafe fn descriptors<'a>(
tensors: *const ffi::RuneCoralTensor,
len: u64,
) -> impl Iterator<Item = TensorDescriptor<'a>> {
let tensors = if len > 0 {
std::slice::from_raw_parts(tensors, len as usize)
} else {
&[]
};
tensors.iter().map(TensorDescriptor::from_rune_coral_tensor)
}
impl Debug for InferenceContext {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("InferenceContext").finish_non_exhaustive()
}
}
impl Drop for InferenceContext {
fn drop(&mut self) {
unsafe {
ffi::destroy_inference_context(self.ctx.as_ptr());
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, thiserror::Error)]
pub enum LoadError {
#[error("Incorrect mimetype")]
IncorrectMimeType,
#[error("Internal error")]
InternalError,
#[error("Unknown error {}", return_code)]
Other {
return_code: ffi::RuneCoralLoadResult,
},
}
fn check_load_result(return_code: ffi::RuneCoralLoadResult) -> Result<(), LoadError> {
match return_code {
ffi::RuneCoralLoadResult__Ok => Ok(()),
ffi::RuneCoralLoadResult__IncorrectMimeType => Err(LoadError::IncorrectMimeType),
ffi::RuneCoralLoadResult__InternalError => Err(LoadError::InternalError),
_ => Err(LoadError::Other { return_code }),
}
}
unsafe impl Send for InferenceContext {}
fn check_inference_error(return_code: ffi::RuneCoralInferenceResult) -> Result<(), InferError> {
match return_code {
ffi::RuneCoralInferenceResult__Ok => Ok(()),
ffi::RuneCoralInferenceResult__Error => Err(InferError::InterpreterError),
ffi::RuneCoralInferenceResult__DelegateError => Err(InferError::DelegateError),
ffi::RuneCoralInferenceResult__ApplicationError => Err(InferError::ApplicationError),
_ => Err(InferError::Other { return_code }),
}
}
#[derive(Debug, Copy, Clone, PartialEq, thiserror::Error)]
pub enum InferError {
#[error("The TensorFlow Lite interpreter encountered an error")]
InterpreterError,
#[error("A delegate returned an error")]
DelegateError,
#[error("Invalid model graph or incompatibility between runtime and delegates")]
ApplicationError,
#[error("Unknown inference error {}", return_code)]
Other {
return_code: ffi::RuneCoralInferenceResult,
},
}
bitflags! {
pub struct AccelerationBackend: u32 {
const NONE = ffi::RuneCoralAccelerationBackend__None as u32;
const EDGETPU = ffi::RuneCoralAccelerationBackend__Edgetpu as u32;
const GPU = ffi::RuneCoralAccelerationBackend__Gpu as u32;
}
}
impl AccelerationBackend {
pub fn currently_available() -> Self {
unsafe {
AccelerationBackend::from_bits(ffi::availableAccelerationBackends() as u32).unwrap()
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::*;
#[test]
fn inference_context_is_only_send() {
static_assertions::assert_impl_all!(InferenceContext: Send);
static_assertions::assert_not_impl_any!(InferenceContext: Sync);
static_assertions::assert_impl_all!(Mutex<InferenceContext>: Send, Sync);
}
}