Files
leleka/crates/openvino/src/lib.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 8d96e9c44c perf: overlap weight expansion with NPU execution, batch products, SIMD half conversion, graph cache (STRA-207)
- service: BATCH n lets it see each product's successor and expand the next weights on a thread
  while the device runs the current one; buckets up to 4096; OpenVINO CACHE_DIR compile cache
- client: batched expert products, layout sized by batch, default batch 2048
- cpu-sys/cpu-kernels: AVX2 F16C f16_to_f32 kernel, exact for every half bit pattern
- npu-worker: memory admission before an NPU prefill (falls back to the CPU when RAM is short)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 12:22:13 +02:00

677 lines
23 KiB
Rust

//! A minimal, safe-looking binding to the OpenVINO C API (`openvino_c.dll` / `libopenvino_c.so`).
//!
//! The library is loaded at run time from a path the caller gives (nothing is linked, nothing is searched for
//! beyond what the operating system does for the library's own dependencies, so the directory of the other
//! OpenVINO files must be on the loader path). Only what the NPU service needs exists: devices, reading an IR
//! model from memory, compiling it, host tensors, and synchronous inference.
//!
//! Every handle keeps the loaded library alive and frees its C object on drop. OpenVINO objects may be used
//! from one thread at a time; the types are `Send` but not `Sync`.
use libloading::{Library, Symbol};
use std::ffi::{CStr, CString, c_char, c_void};
use std::fmt;
use std::sync::Arc;
#[derive(Debug)]
pub enum Error {
/// The library or one of its symbols could not be loaded.
Load(String),
/// An OpenVINO call returned a failure status.
Call {
what: &'static str,
status: i32,
message: String,
},
/// Arguments that cannot be valid (sizes, shapes).
Invalid(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Load(m) => write!(f, "cannot load OpenVINO: {m}"),
Self::Call {
what,
status,
message,
} => write!(f, "{what} failed (status {status}): {message}"),
Self::Invalid(m) => write!(f, "invalid argument: {m}"),
}
}
}
impl std::error::Error for Error {}
/// Element types by their `ov_element_type_e` value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum Element {
F16 = 3,
F32 = 4,
I8 = 7,
I32 = 9,
U8 = 16,
}
impl Element {
pub fn bytes(self) -> usize {
match self {
Self::F16 => 2,
Self::F32 | Self::I32 => 4,
Self::I8 | Self::U8 => 1,
}
}
}
#[repr(C)]
struct RawShape {
rank: i64,
dims: *mut i64,
}
#[repr(C)]
struct RawDevices {
devices: *mut *mut c_char,
size: usize,
}
type Status = i32;
struct Fns {
err_msg: unsafe extern "C" fn() -> *const c_char,
core_create: unsafe extern "C" fn(*mut *mut c_void) -> Status,
core_free: unsafe extern "C" fn(*mut c_void),
get_devices: unsafe extern "C" fn(*const c_void, *mut RawDevices) -> Status,
free_devices: unsafe extern "C" fn(*mut RawDevices),
get_property: unsafe extern "C" fn(
*const c_void,
*const c_char,
*const c_char,
*mut *mut c_char,
) -> Status,
free_str: unsafe extern "C" fn(*const c_char),
read_model_mem: unsafe extern "C" fn(
*const c_void,
*const c_char,
usize,
*const c_void,
*mut *mut c_void,
) -> Status,
model_free: unsafe extern "C" fn(*mut c_void),
compile: unsafe extern "C" fn(
*const c_void,
*const c_void,
*const c_char,
usize,
*mut *mut c_void,
...
) -> Status,
compiled_free: unsafe extern "C" fn(*mut c_void),
new_request: unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status,
request_free: unsafe extern "C" fn(*mut c_void),
set_input: unsafe extern "C" fn(*mut c_void, usize, *const c_void) -> Status,
get_output: unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> Status,
infer: unsafe extern "C" fn(*mut c_void) -> Status,
shape_create: unsafe extern "C" fn(i64, *const i64, *mut RawShape) -> Status,
shape_free: unsafe extern "C" fn(*mut RawShape) -> Status,
tensor_create: unsafe extern "C" fn(u32, RawShape, *mut *mut c_void) -> Status,
tensor_from_host: unsafe extern "C" fn(u32, RawShape, *mut c_void, *mut *mut c_void) -> Status,
tensor_data: unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status,
tensor_free: unsafe extern "C" fn(*mut c_void),
}
/// The loaded library and its entry points.
pub struct OpenVino {
fns: Fns,
_lib: Library,
}
macro_rules! load {
($lib:expr, $name:literal, $ty:ty) => {{
// SAFETY: the symbol is looked up by name and given the signature of the OpenVINO C header.
let s: Symbol<$ty> = unsafe { $lib.get($name.as_bytes()) }
.map_err(|e| Error::Load(format!("{}: {e}", $name)))?;
*s
}};
}
impl OpenVino {
/// Load `openvino_c.dll` (or the platform's name) from `path`.
pub fn load(path: &std::path::Path) -> Result<Arc<Self>, Error> {
// SAFETY: loading a library runs its initialisation code; the caller names the file.
let lib = unsafe { Library::new(path) }
.map_err(|e| Error::Load(format!("{}: {e}", path.display())))?;
let fns = Fns {
err_msg: load!(
lib,
"ov_get_last_err_msg",
unsafe extern "C" fn() -> *const c_char
),
core_create: load!(
lib,
"ov_core_create",
unsafe extern "C" fn(*mut *mut c_void) -> Status
),
core_free: load!(lib, "ov_core_free", unsafe extern "C" fn(*mut c_void)),
get_devices: load!(
lib,
"ov_core_get_available_devices",
unsafe extern "C" fn(*const c_void, *mut RawDevices) -> Status
),
free_devices: load!(
lib,
"ov_available_devices_free",
unsafe extern "C" fn(*mut RawDevices)
),
get_property: load!(
lib,
"ov_core_get_property",
unsafe extern "C" fn(
*const c_void,
*const c_char,
*const c_char,
*mut *mut c_char,
) -> Status
),
free_str: load!(lib, "ov_free", unsafe extern "C" fn(*const c_char)),
read_model_mem: load!(
lib,
"ov_core_read_model_from_memory_buffer",
unsafe extern "C" fn(
*const c_void,
*const c_char,
usize,
*const c_void,
*mut *mut c_void,
) -> Status
),
model_free: load!(lib, "ov_model_free", unsafe extern "C" fn(*mut c_void)),
compile: load!(
lib,
"ov_core_compile_model",
unsafe extern "C" fn(
*const c_void,
*const c_void,
*const c_char,
usize,
*mut *mut c_void,
...
) -> Status
),
compiled_free: load!(
lib,
"ov_compiled_model_free",
unsafe extern "C" fn(*mut c_void)
),
new_request: load!(
lib,
"ov_compiled_model_create_infer_request",
unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status
),
request_free: load!(
lib,
"ov_infer_request_free",
unsafe extern "C" fn(*mut c_void)
),
set_input: load!(
lib,
"ov_infer_request_set_input_tensor_by_index",
unsafe extern "C" fn(*mut c_void, usize, *const c_void) -> Status
),
get_output: load!(
lib,
"ov_infer_request_get_output_tensor_by_index",
unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> Status
),
infer: load!(
lib,
"ov_infer_request_infer",
unsafe extern "C" fn(*mut c_void) -> Status
),
shape_create: load!(
lib,
"ov_shape_create",
unsafe extern "C" fn(i64, *const i64, *mut RawShape) -> Status
),
shape_free: load!(
lib,
"ov_shape_free",
unsafe extern "C" fn(*mut RawShape) -> Status
),
tensor_create: load!(
lib,
"ov_tensor_create",
unsafe extern "C" fn(u32, RawShape, *mut *mut c_void) -> Status
),
tensor_from_host: load!(
lib,
"ov_tensor_create_from_host_ptr",
unsafe extern "C" fn(u32, RawShape, *mut c_void, *mut *mut c_void) -> Status
),
tensor_data: load!(
lib,
"ov_tensor_data",
unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status
),
tensor_free: load!(lib, "ov_tensor_free", unsafe extern "C" fn(*mut c_void)),
};
Ok(Arc::new(Self { fns, _lib: lib }))
}
fn check(&self, status: Status, what: &'static str) -> Result<(), Error> {
if status == 0 {
return Ok(());
}
// SAFETY: the function returns a NUL-terminated string owned by the library, or null.
let message = unsafe {
let p = (self.fns.err_msg)();
if p.is_null() {
String::new()
} else {
CStr::from_ptr(p).to_string_lossy().into_owned()
}
};
Err(Error::Call {
what,
status,
message,
})
}
}
/// An OpenVINO core: device discovery and model compilation.
pub struct Core {
ov: Arc<OpenVino>,
raw: *mut c_void,
cache_dir: Option<CString>,
}
// SAFETY: the core is used from one thread at a time (no Sync), and moving it between threads is allowed by
// the C API.
unsafe impl Send for Core {}
impl Core {
pub fn new(ov: &Arc<OpenVino>) -> Result<Self, Error> {
let mut raw = std::ptr::null_mut();
// SAFETY: `raw` is a valid out pointer.
ov.check(unsafe { (ov.fns.core_create)(&mut raw) }, "ov_core_create")?;
Ok(Self {
ov: ov.clone(),
raw,
cache_dir: None,
})
}
/// Keep compiled blobs in `dir` (OpenVINO's `CACHE_DIR` property): compiling the same model again, in this
/// or a later process, imports the blob instead of compiling.
pub fn with_cache_dir(mut self, dir: &std::path::Path) -> Result<Self, Error> {
std::fs::create_dir_all(dir)
.map_err(|e| Error::Invalid(format!("{}: {e}", dir.display())))?;
self.cache_dir = Some(cstring(&dir.to_string_lossy())?);
Ok(self)
}
/// Names of the devices OpenVINO can use, such as `CPU`, `GPU`, `NPU`.
pub fn devices(&self) -> Result<Vec<String>, Error> {
let mut raw = RawDevices {
devices: std::ptr::null_mut(),
size: 0,
};
// SAFETY: valid core and out pointer.
self.ov.check(
unsafe { (self.ov.fns.get_devices)(self.raw, &mut raw) },
"ov_core_get_available_devices",
)?;
let names = (0..raw.size)
// SAFETY: the array holds `size` NUL-terminated strings until it is freed below.
.map(|i| {
unsafe { CStr::from_ptr(*raw.devices.add(i)) }
.to_string_lossy()
.into_owned()
})
.collect();
// SAFETY: the structure was filled by the call above and is freed once.
unsafe { (self.ov.fns.free_devices)(&mut raw) };
Ok(names)
}
/// A string property of a device, such as `FULL_DEVICE_NAME`.
pub fn property(&self, device: &str, key: &str) -> Result<String, Error> {
let (d, k) = (cstring(device)?, cstring(key)?);
let mut out = std::ptr::null_mut();
// SAFETY: valid core, NUL-terminated strings and out pointer.
self.ov.check(
unsafe { (self.ov.fns.get_property)(self.raw, d.as_ptr(), k.as_ptr(), &mut out) },
"ov_core_get_property",
)?;
// SAFETY: on success `out` is a NUL-terminated string allocated by the library, freed once.
let value = unsafe { CStr::from_ptr(out) }
.to_string_lossy()
.into_owned();
unsafe { (self.ov.fns.free_str)(out) };
Ok(value)
}
/// Compile the IR model `xml` whose constants are in `weights` for `device`.
pub fn compile(&self, device: &str, xml: &str, weights: &[u8]) -> Result<Compiled, Error> {
let wt = Tensor::from_bytes(
&self.ov,
Element::U8,
&[weights.len().max(1) as i64],
weights,
)?;
let mut model = std::ptr::null_mut();
// SAFETY: valid core, the XML text with its length, a valid tensor and an out pointer.
self.ov.check(
unsafe {
(self.ov.fns.read_model_mem)(
self.raw,
xml.as_ptr().cast(),
xml.len(),
wt.raw,
&mut model,
)
},
"ov_core_read_model_from_memory_buffer",
)?;
let d = cstring(device)?;
let mut compiled = std::ptr::null_mut();
let key = cstring("CACHE_DIR")?;
// SAFETY: valid core, model and device name; the variadic tail is empty or one (key, value) pair of
// NUL-terminated strings that live through the call, announced by the count of 2 (the C API counts the arguments, not the pairs).
let status = unsafe {
match &self.cache_dir {
Some(dir) => (self.ov.fns.compile)(
self.raw,
model,
d.as_ptr(),
2usize,
&mut compiled,
key.as_ptr(),
dir.as_ptr(),
),
None => (self.ov.fns.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled),
}
};
// SAFETY: the model was created above and is not needed once compiled (or if compiling failed).
unsafe { (self.ov.fns.model_free)(model) };
self.ov.check(status, "ov_core_compile_model")?;
Ok(Compiled {
ov: self.ov.clone(),
raw: compiled,
})
}
}
impl Drop for Core {
fn drop(&mut self) {
// SAFETY: created by ov_core_create, freed once.
unsafe { (self.ov.fns.core_free)(self.raw) };
}
}
/// A model compiled for a device.
pub struct Compiled {
ov: Arc<OpenVino>,
raw: *mut c_void,
}
// SAFETY: as for `Core`.
unsafe impl Send for Compiled {}
impl Compiled {
pub fn request(&self) -> Result<Request, Error> {
let mut raw = std::ptr::null_mut();
// SAFETY: valid compiled model and out pointer.
self.ov.check(
unsafe { (self.ov.fns.new_request)(self.raw, &mut raw) },
"ov_compiled_model_create_infer_request",
)?;
Ok(Request {
ov: self.ov.clone(),
raw,
})
}
}
impl Drop for Compiled {
fn drop(&mut self) {
// SAFETY: created by ov_core_compile_model, freed once.
unsafe { (self.ov.fns.compiled_free)(self.raw) };
}
}
/// An inference request: set the inputs, run, read the outputs.
pub struct Request {
ov: Arc<OpenVino>,
raw: *mut c_void,
}
// SAFETY: as for `Core`.
unsafe impl Send for Request {}
impl Request {
/// Bind `tensor` as input number `index`. The request reads it at every `infer` until it is replaced,
/// so the tensor must stay alive (and may be rewritten between runs).
pub fn set_input(&mut self, index: usize, tensor: &Tensor) -> Result<(), Error> {
// SAFETY: valid request and tensor.
self.ov.check(
unsafe { (self.ov.fns.set_input)(self.raw, index, tensor.raw) },
"ov_infer_request_set_input_tensor_by_index",
)
}
pub fn infer(&mut self) -> Result<(), Error> {
// SAFETY: valid request.
self.ov.check(
unsafe { (self.ov.fns.infer)(self.raw) },
"ov_infer_request_infer",
)
}
/// Output number `index` of the last run. The tensor is owned by the caller (a handle to the request's
/// buffer): read it before the next `infer`.
pub fn output(&self, index: usize) -> Result<Tensor, Error> {
let mut raw = std::ptr::null_mut();
// SAFETY: valid request and out pointer.
self.ov.check(
unsafe { (self.ov.fns.get_output)(self.raw, index, &mut raw) },
"ov_infer_request_get_output_tensor_by_index",
)?;
Ok(Tensor {
ov: self.ov.clone(),
raw,
bytes: usize::MAX,
})
}
}
impl Drop for Request {
fn drop(&mut self) {
// SAFETY: created by ov_compiled_model_create_infer_request, freed once.
unsafe { (self.ov.fns.request_free)(self.raw) };
}
}
/// A host tensor.
pub struct Tensor {
ov: Arc<OpenVino>,
raw: *mut c_void,
/// Size in bytes when known (tensors created here); `usize::MAX` for output handles.
bytes: usize,
}
// SAFETY: as for `Core`.
unsafe impl Send for Tensor {}
fn cstring(s: &str) -> Result<CString, Error> {
CString::new(s).map_err(|_| Error::Invalid(format!("{s:?} contains a NUL byte")))
}
fn with_shape<T>(
ov: &OpenVino,
dims: &[i64],
f: impl FnOnce(RawShape) -> Result<T, Error>,
) -> Result<T, Error> {
let mut shape = RawShape {
rank: 0,
dims: std::ptr::null_mut(),
};
// SAFETY: `dims` is valid for its length and `shape` is a valid out pointer.
ov.check(
unsafe { (ov.fns.shape_create)(dims.len() as i64, dims.as_ptr(), &mut shape) },
"ov_shape_create",
)?;
// The tensor constructors copy the dimensions, so the shape can be freed right after the call.
let result = f(RawShape {
rank: shape.rank,
dims: shape.dims,
});
// SAFETY: the shape was created above and is freed once.
unsafe { (ov.fns.shape_free)(&mut shape) };
result
}
impl Tensor {
/// A new tensor owned by OpenVINO, uninitialised.
pub fn new(ov: &Arc<OpenVino>, element: Element, dims: &[i64]) -> Result<Self, Error> {
let mut raw = std::ptr::null_mut();
// SAFETY: the shape is valid for the call; `raw` is a valid out pointer.
with_shape(ov, dims, |shape| {
ov.check(
unsafe { (ov.fns.tensor_create)(element as u32, shape, &mut raw) },
"ov_tensor_create",
)
})?;
let bytes = element.bytes() * dims.iter().product::<i64>().max(0) as usize;
Ok(Self {
ov: ov.clone(),
raw,
bytes,
})
}
/// A new tensor holding a copy of `data`.
pub fn from_bytes(
ov: &Arc<OpenVino>,
element: Element,
dims: &[i64],
data: &[u8],
) -> Result<Self, Error> {
let mut t = Self::new(ov, element, dims)?;
t.write(0, data)?;
Ok(t)
}
/// A tensor over caller-owned memory (not copied). The memory must outlive the tensor and the requests
/// it is bound to.
///
/// # Safety
/// `ptr` must point to at least `element.bytes() * product(dims)` valid bytes for as long as the tensor
/// is used, and nothing else may write them during an inference that reads them.
pub unsafe fn over_memory(
ov: &Arc<OpenVino>,
element: Element,
dims: &[i64],
ptr: *mut u8,
) -> Result<Self, Error> {
let mut raw = std::ptr::null_mut();
// SAFETY: forwarded from the caller's contract.
with_shape(ov, dims, |shape| {
ov.check(
unsafe { (ov.fns.tensor_from_host)(element as u32, shape, ptr.cast(), &mut raw) },
"ov_tensor_create_from_host_ptr",
)
})?;
let bytes = element.bytes() * dims.iter().product::<i64>().max(0) as usize;
Ok(Self {
ov: ov.clone(),
raw,
bytes,
})
}
fn data_ptr(&self) -> Result<*mut u8, Error> {
let mut p = std::ptr::null_mut();
// SAFETY: valid tensor and out pointer.
self.ov.check(
unsafe { (self.ov.fns.tensor_data)(self.raw, &mut p) },
"ov_tensor_data",
)?;
Ok(p.cast())
}
/// Copy `data` into the tensor at byte `offset`.
pub fn write(&mut self, offset: usize, data: &[u8]) -> Result<(), Error> {
if self.bytes != usize::MAX && offset.saturating_add(data.len()) > self.bytes {
return Err(Error::Invalid(format!(
"write of {} bytes at {offset} exceeds the tensor's {}",
data.len(),
self.bytes
)));
}
let p = self.data_ptr()?;
// SAFETY: the range was checked against the tensor's size; `data` is separate memory.
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), p.add(offset), data.len()) };
Ok(())
}
/// Copy `out.len()` bytes at byte `offset` out of the tensor. For an output handle the caller vouches
/// for the size (it knows the model's output shape).
pub fn read(&self, offset: usize, out: &mut [u8]) -> Result<(), Error> {
if self.bytes != usize::MAX && offset.saturating_add(out.len()) > self.bytes {
return Err(Error::Invalid(format!(
"read of {} bytes at {offset} exceeds the tensor's {}",
out.len(),
self.bytes
)));
}
let p = self.data_ptr()?;
// SAFETY: as in `write`.
unsafe { std::ptr::copy_nonoverlapping(p.add(offset), out.as_mut_ptr(), out.len()) };
Ok(())
}
/// The tensor's bytes for filling in place (tensors created here only: their size is known).
pub fn bytes_mut(&mut self) -> Result<&mut [u8], Error> {
if self.bytes == usize::MAX {
return Err(Error::Invalid(
"the size of an output handle is not known".into(),
));
}
let p = self.data_ptr()?;
// SAFETY: the tensor owns (or was given) `bytes` valid bytes at `p`, and `&mut self` guarantees no
// other reference to them exists through this handle.
Ok(unsafe { std::slice::from_raw_parts_mut(p, self.bytes) })
}
}
impl Drop for Tensor {
fn drop(&mut self) {
// SAFETY: created by one of the tensor constructors or ov_infer_request_get_output_tensor_by_index,
// each of which returns a handle that is freed exactly once.
unsafe { (self.ov.fns.tensor_free)(self.raw) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_library_is_a_load_error() {
let err = OpenVino::load(std::path::Path::new("definitely-not-there-openvino_c.dll"))
.err()
.unwrap();
assert!(matches!(err, Error::Load(_)), "{err}");
}
#[test]
fn element_sizes() {
assert_eq!(Element::F16.bytes(), 2);
assert_eq!(Element::I8.bytes(), 1);
assert_eq!(Element::F32.bytes(), 4);
}
}