Skip to main content

virtio_accel_openvino/
native.rs

1//! Native OpenVINO runtime integration: the audited `Accelerator` implementation.
2//!
3//! Every `unsafe` block carries a `SAFETY:` comment referencing the invariants audited in
4//! `SAFETY.md`. Each OpenVINO handle has exactly one Rust owner with a `Drop` implementation;
5//! the shared `ov_core_t` is process-wide. Completion is poll-latched: no foreign callback ever
6//! owns Rust memory.
7
8use std::alloc::{Layout, alloc_zeroed, dealloc};
9use std::cell::{Cell, RefCell, RefMut};
10use std::ffi::{CStr, CString, c_void};
11use std::marker::PhantomData;
12use std::mem;
13use std::ops::{Deref, DerefMut};
14use std::ptr::{self, NonNull};
15use std::rc::{Rc, Weak};
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Arc, OnceLock};
18use std::time::{Duration, Instant};
19
20use virtio_accel_core::{
21    Accelerator, AcceleratorClass, AccessMode, AllocatedBuffer, ArtifactRef, BackendError,
22    BindingRef, BufferDesc, BufferInfo, BufferProperties, BufferUsage, ByteSink, ByteSource,
23    Capabilities, ContextDesc, DeviceIdentity, DeviceInfo, DeviceLimits, EventState, MemoryDomain,
24    QueueDesc, ReleaseFailure, SubmitFailure, Timeout,
25};
26use virtio_accel_tosa::{CapabilityDescriptor, TosaCapabilityProvider};
27
28use crate::lower::{LoweredFeature, LoweredFeatureRole, OvElement, lower_tosa_with_weights};
29use crate::{InitError, REQUIRED_RESIDENT_BYTES, ffi};
30
31/// Maximal TOSA artifact bytes admitted before parsing.
32const MAX_TOSA_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
33
34/// Minimum allocation alignment: one page, satisfying every plugin's zero-copy import rules.
35const OPENVINO_MIN_ALIGNMENT: usize = 4096;
36
37/// Stack scratch size for segmented explicit transfers.
38const TRANSFER_CHUNK_BYTES: usize = 16 * 1024;
39
40/// Stable provider-owned error namespace for unmapped OpenVINO statuses (`"OVNO"`).
41const OPENVINO_EXTERNAL_DOMAIN: u32 = 0x4f56_4e4f;
42
43const EXCLUSIVE_NATIVE_ACCESS: u64 = 1 << 63;
44const MAX_SHARED_NATIVE_USERS: u64 = EXCLUSIVE_NATIVE_ACCESS - 1;
45
46/// Owned `ov_core_t`; in practice held by [`shared_core`] for the process lifetime.
47struct CoreHandle {
48    core: NonNull<ffi::ov_core_t>,
49}
50
51// SAFETY: `ov::Core` is documented thread-safe by OpenVINO and the C wrapper adds no thread
52// affinity; the handle is freed exactly once by `Drop`.
53unsafe impl Send for CoreHandle {}
54// SAFETY: shared `&CoreHandle` use only reaches thread-safe `ov_core_*` entry points.
55unsafe impl Sync for CoreHandle {}
56
57/// The process-wide OpenVINO core.
58///
59/// Exactly one `ov_core_t` is created per process and lives until process exit. Re-initializing
60/// the runtime is not crash-safe: a second `ov_core_create` re-creates plugin engines, and the
61/// Intel NPU plugin's second `zeInitDrivers` call segfaults inside the Level Zero loader
62/// (observed with ze_loader 1.28 and OpenVINO 2026.3 on hosts without a vendor driver). Every
63/// accelerator instance shares this core; contexts, buffers, programs, queues, and events remain
64/// per-instance state.
65fn shared_core() -> Result<Arc<CoreHandle>, InitError> {
66    ffi::ensure_loaded()?;
67    static CORE: OnceLock<Result<Arc<CoreHandle>, InitError>> = OnceLock::new();
68    CORE.get_or_init(|| CoreHandle::create().map(Arc::new))
69        .clone()
70}
71
72impl CoreHandle {
73    fn create() -> Result<Self, InitError> {
74        let mut core = ptr::null_mut();
75        // SAFETY: `core` is a valid out-pointer; the runtime initializes it only on OK.
76        let status = unsafe { (ffi::api().ov_core_create)(&mut core) };
77        if status != ffi::OV_STATUS_OK {
78            return Err(InitError::CoreCreationFailed);
79        }
80        NonNull::new(core)
81            .map(|core| Self { core })
82            .ok_or(InitError::CoreCreationFailed)
83    }
84
85    const fn as_const_ptr(&self) -> *const ffi::ov_core_t {
86        self.core.as_ptr()
87    }
88
89    /// Enumerate inference device names through this core.
90    fn available_devices(&self) -> Result<Vec<String>, InitError> {
91        let mut devices = ffi::ov_available_devices_t {
92            devices: ptr::null_mut(),
93            size: 0,
94        };
95        // SAFETY: the core is live and `devices` is a valid out-structure the runtime fills on
96        // OK; on failure it stays in its zeroed state and must not be freed.
97        let status = unsafe {
98            (ffi::api().ov_core_get_available_devices)(self.as_const_ptr(), &mut devices)
99        };
100        if status != ffi::OV_STATUS_OK {
101            return Err(InitError::DeviceEnumerationFailed);
102        }
103        let mut names = Vec::with_capacity(devices.size);
104        // SAFETY: on OK the runtime owns `devices.size` NUL-terminated names; they are copied
105        // before the single required `ov_available_devices_free` call releases them.
106        unsafe {
107            for index in 0..devices.size {
108                let name = *devices.devices.add(index);
109                if !name.is_null() {
110                    names.push(CStr::from_ptr(name).to_string_lossy().into_owned());
111                }
112            }
113            (ffi::api().ov_available_devices_free)(&mut devices);
114        }
115        Ok(names)
116    }
117}
118
119impl Drop for CoreHandle {
120    fn drop(&mut self) {
121        // SAFETY: the handle owns exactly one core reference and is dropped exactly once.
122        unsafe { (ffi::api().ov_core_free)(self.core.as_ptr()) }
123    }
124}
125
126fn backend_error_from_status(status: ffi::ov_status_e) -> BackendError {
127    match status {
128        ffi::OV_STATUS_NOT_IMPLEMENTED | ffi::OV_STATUS_NOT_IMPLEMENT_C_METHOD => {
129            BackendError::Unsupported
130        }
131        ffi::OV_STATUS_PARAMETER_MISMATCH => BackendError::Incompatible,
132        ffi::OV_STATUS_NOT_FOUND | ffi::OV_STATUS_INVALID_C_PARAM => BackendError::InvalidArgument,
133        ffi::OV_STATUS_OUT_OF_BOUNDS => BackendError::OutOfBounds,
134        ffi::OV_STATUS_REQUEST_BUSY => BackendError::Busy,
135        ffi::OV_STATUS_NOT_ALLOCATED => BackendError::OutOfMemory,
136        other => BackendError::External {
137            domain: OPENVINO_EXTERNAL_DOMAIN,
138            code: i64::from(other),
139        },
140    }
141}
142
143fn check_status(status: ffi::ov_status_e) -> Result<(), BackendError> {
144    if status == ffi::OV_STATUS_OK {
145        Ok(())
146    } else {
147        Err(backend_error_from_status(status))
148    }
149}
150
151/// Page-aligned buffer backing directly wrapped by OpenVINO tensors.
152#[derive(Debug)]
153struct AlignedAllocation {
154    pointer: NonNull<u8>,
155    layout: Layout,
156    in_flight: AtomicU64,
157}
158
159impl AlignedAllocation {
160    fn new(bytes: u64, requested_alignment: u64) -> Result<Self, BackendError> {
161        let bytes = usize::try_from(bytes).map_err(|_| BackendError::OutOfMemory)?;
162        let requested_alignment =
163            usize::try_from(requested_alignment).map_err(|_| BackendError::OutOfMemory)?;
164        let alignment = requested_alignment.max(OPENVINO_MIN_ALIGNMENT);
165        let allocation_bytes = bytes
166            .checked_add(alignment - 1)
167            .map(|value| value & !(alignment - 1))
168            .ok_or(BackendError::OutOfMemory)?;
169        let layout = Layout::from_size_align(allocation_bytes, alignment)
170            .map_err(|_| BackendError::OutOfMemory)?;
171        // SAFETY: `layout` is valid and nonzero. The returned pointer is owned by this value and
172        // is released with the identical layout in `Drop`.
173        let pointer =
174            NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(BackendError::OutOfMemory)?;
175        Ok(Self {
176            pointer,
177            layout,
178            in_flight: AtomicU64::new(0),
179        })
180    }
181
182    fn allocation_bytes(&self) -> u64 {
183        self.layout.size() as u64
184    }
185
186    fn alignment(&self) -> u64 {
187        self.layout.align() as u64
188    }
189
190    fn pointer_at(&self, offset: usize) -> *mut u8 {
191        // SAFETY: every caller first validates `offset` against the allocation's logical buffer
192        // range, which is no larger than this layout.
193        unsafe { self.pointer.as_ptr().add(offset) }
194    }
195}
196
197// SAFETY: allocation access is available only through the `Accelerator` methods. The buffer
198// handle is neither Send nor Sync, and its atomic in-flight gate excludes host transfers while a
199// native inference owns a backing guard. Guards are dropped strictly before an event's terminal
200// state becomes observable. See `SAFETY.md`.
201unsafe impl Send for AlignedAllocation {}
202// SAFETY: same invariant as the `Send` implementation.
203unsafe impl Sync for AlignedAllocation {}
204
205impl Drop for AlignedAllocation {
206    fn drop(&mut self) {
207        // SAFETY: `pointer` was returned by `alloc_zeroed(self.layout)` and has not been freed.
208        unsafe { dealloc(self.pointer.as_ptr(), self.layout) };
209    }
210}
211
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213enum BackingAccess {
214    Shared,
215    Exclusive,
216}
217
218impl BackingAccess {
219    const fn for_binding(access: AccessMode) -> Self {
220        match access {
221            AccessMode::Read => Self::Shared,
222            AccessMode::Write | AccessMode::ReadWrite => Self::Exclusive,
223        }
224    }
225
226    const fn combine(self, other: Self) -> Self {
227        if matches!(self, Self::Exclusive) || matches!(other, Self::Exclusive) {
228            Self::Exclusive
229        } else {
230            Self::Shared
231        }
232    }
233}
234
235/// In-flight guard for one allocation bound to one submission.
236#[derive(Debug)]
237struct EventBacking {
238    key: usize,
239    allocation: Arc<AlignedAllocation>,
240    access: BackingAccess,
241    acquired: bool,
242}
243
244impl EventBacking {
245    fn new(allocation: Arc<AlignedAllocation>, access: AccessMode) -> Self {
246        Self {
247            key: Arc::as_ptr(&allocation) as usize,
248            allocation,
249            access: BackingAccess::for_binding(access),
250            acquired: false,
251        }
252    }
253
254    // `try_update` is not available on our Rust 1.85 MSRV. Keep the equivalent
255    // `fetch_update` operation until the minimum compiler supports its new name.
256    #[allow(deprecated)]
257    fn acquire(&mut self) -> Result<(), BackendError> {
258        match self.access {
259            BackingAccess::Shared => {
260                self.allocation
261                    .in_flight
262                    .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
263                        (current < MAX_SHARED_NATIVE_USERS).then_some(current + 1)
264                    })
265                    .map_err(|_| BackendError::Busy)?;
266            }
267            BackingAccess::Exclusive => {
268                self.allocation
269                    .in_flight
270                    .compare_exchange(
271                        0,
272                        EXCLUSIVE_NATIVE_ACCESS,
273                        Ordering::AcqRel,
274                        Ordering::Acquire,
275                    )
276                    .map_err(|_| BackendError::Busy)?;
277            }
278        }
279        self.acquired = true;
280        Ok(())
281    }
282}
283
284/// Collapse duplicate allocations to their strongest access, then acquire every guard.
285fn prepare_event_backings(backings: &mut Vec<EventBacking>) -> Result<(), BackendError> {
286    backings.sort_unstable_by_key(|backing| backing.key);
287    backings.dedup_by(|current, previous| {
288        if current.key != previous.key {
289            return false;
290        }
291        previous.access = previous.access.combine(current.access);
292        true
293    });
294    for backing in backings {
295        backing.acquire()?;
296    }
297    Ok(())
298}
299
300impl Drop for EventBacking {
301    fn drop(&mut self) {
302        if !self.acquired {
303            return;
304        }
305        match self.access {
306            BackingAccess::Shared => {
307                let prior = self.allocation.in_flight.fetch_sub(1, Ordering::Release);
308                debug_assert!((1..=MAX_SHARED_NATIVE_USERS).contains(&prior));
309            }
310            BackingAccess::Exclusive => {
311                let result = self.allocation.in_flight.compare_exchange(
312                    EXCLUSIVE_NATIVE_ACCESS,
313                    0,
314                    Ordering::Release,
315                    Ordering::Relaxed,
316                );
317                debug_assert_eq!(result, Ok(EXCLUSIVE_NATIVE_ACCESS));
318            }
319        }
320    }
321}
322
323/// Owned `ov_shape_t`, created once per program slot and reused across submissions.
324struct OwnedShape {
325    shape: ffi::ov_shape_t,
326}
327
328impl OwnedShape {
329    fn new(dims: &[i64]) -> Result<Self, BackendError> {
330        let mut shape = ffi::ov_shape_t {
331            rank: 0,
332            dims: ptr::null_mut(),
333        };
334        // SAFETY: `dims` is a live slice and `shape` a valid out-structure; the runtime copies
335        // the dims into its own allocation, released exactly once in `Drop`.
336        check_status(unsafe {
337            (ffi::api().ov_shape_create)(dims.len() as i64, dims.as_ptr(), &mut shape)
338        })?;
339        Ok(Self { shape })
340    }
341
342    /// By-value view for C calls that copy the shape (tensor creation).
343    const fn as_value(&self) -> ffi::ov_shape_t {
344        self.shape
345    }
346}
347
348impl Drop for OwnedShape {
349    fn drop(&mut self) {
350        // SAFETY: `shape` was initialized by `ov_shape_create` and is freed exactly once.
351        let _ = unsafe { (ffi::api().ov_shape_free)(&mut self.shape) };
352    }
353}
354
355/// Owned `ov_tensor_t`.
356struct TensorHandle {
357    tensor: NonNull<ffi::ov_tensor_t>,
358}
359
360impl TensorHandle {
361    /// Wrap caller-owned memory; the tensor never frees `data`, whose region must stay live and
362    /// unmoved for this handle's lifetime.
363    fn from_host_ptr(
364        element: ffi::ov_element_type_e,
365        shape: ffi::ov_shape_t,
366        data: *mut c_void,
367    ) -> Result<Self, BackendError> {
368        let mut tensor = ptr::null_mut();
369        // SAFETY: the shape is initialized, `data` addresses a live region large enough for the
370        // shape/element pair (validated by the caller), and the runtime wraps it without
371        // ownership.
372        check_status(unsafe {
373            (ffi::api().ov_tensor_create_from_host_ptr)(element, shape, data, &mut tensor)
374        })?;
375        NonNull::new(tensor)
376            .map(|tensor| Self { tensor })
377            .ok_or(BackendError::External {
378                domain: OPENVINO_EXTERNAL_DOMAIN,
379                code: 0,
380            })
381    }
382
383    const fn as_const_ptr(&self) -> *const ffi::ov_tensor_t {
384        self.tensor.as_ptr()
385    }
386}
387
388impl Drop for TensorHandle {
389    fn drop(&mut self) {
390        // SAFETY: this handle owns one tensor reference and is dropped exactly once.
391        unsafe { (ffi::api().ov_tensor_free)(self.tensor.as_ptr()) }
392    }
393}
394
395/// One event-owned tensor plus the information needed to verify direct output backing.
396///
397/// Inputs use a null `expected_output`; output buffer pointers are always non-null because they
398/// originate in a live [`AlignedAllocation`]. Keeping the verification metadata beside the
399/// tensor removes a second per-event allocation.
400struct BoundTensor {
401    _tensor: TensorHandle,
402    output_io_index: usize,
403    expected_output: *mut c_void,
404}
405
406#[derive(Default)]
407struct EventMetadata {
408    tensors: Vec<BoundTensor>,
409    backings: Vec<EventBacking>,
410}
411
412/// Queue-owned warm-path metadata capacity.
413///
414/// Only one empty vector of each kind is retained. Returned vectors are cleared before entering
415/// the spare slots, so this object never owns an OpenVINO handle, a buffer backing guard, or a
416/// guest-memory pointer. Events hold a weak reference so outstanding work cannot keep a queue
417/// alive after its owner destroys it.
418#[derive(Default)]
419struct QueueScratch {
420    pointer_slots: RefCell<Vec<*mut c_void>>,
421    metadata_spare: RefCell<Option<EventMetadata>>,
422}
423
424impl QueueScratch {
425    fn take_pointer_slots(&self, count: usize) -> Result<PointerSlots<'_>, BackendError> {
426        let mut slots = self.pointer_slots.borrow_mut();
427        slots.clear();
428        slots
429            .try_reserve(count)
430            .map_err(|_| BackendError::OutOfMemory)?;
431        slots.resize(count, ptr::null_mut());
432        Ok(PointerSlots { slots })
433    }
434
435    fn take_metadata(
436        &self,
437        backing_count: usize,
438        tensor_count: usize,
439    ) -> Result<EventMetadata, BackendError> {
440        let mut metadata = self.metadata_spare.borrow_mut().take().unwrap_or_default();
441        debug_assert!(metadata.backings.is_empty());
442        debug_assert!(metadata.tensors.is_empty());
443        metadata
444            .backings
445            .try_reserve_exact(backing_count)
446            .map_err(|_| BackendError::OutOfMemory)?;
447        metadata
448            .tensors
449            .try_reserve_exact(tensor_count)
450            .map_err(|_| BackendError::OutOfMemory)?;
451        Ok(metadata)
452    }
453
454    fn recycle_metadata(&self, mut returned: EventMetadata) {
455        returned.tensors.clear();
456        returned.backings.clear();
457        let mut spare = self.metadata_spare.borrow_mut();
458        let returned_capacity = returned
459            .tensors
460            .capacity()
461            .saturating_add(returned.backings.capacity());
462        if spare.as_ref().is_none_or(|current| {
463            current
464                .tensors
465                .capacity()
466                .saturating_add(current.backings.capacity())
467                < returned_capacity
468        }) {
469            *spare = Some(returned);
470        }
471    }
472}
473
474impl std::fmt::Debug for QueueScratch {
475    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        formatter
477            .debug_struct("QueueScratch")
478            .field("pointer_capacity", &self.pointer_slots.borrow().capacity())
479            .field(
480                "backing_capacity",
481                &self
482                    .metadata_spare
483                    .borrow()
484                    .as_ref()
485                    .map_or(0, |metadata| metadata.backings.capacity()),
486            )
487            .field(
488                "tensor_capacity",
489                &self
490                    .metadata_spare
491                    .borrow()
492                    .as_ref()
493                    .map_or(0, |metadata| metadata.tensors.capacity()),
494            )
495            .finish()
496    }
497}
498
499/// Borrowed queue pointer slots that are scrubbed on every exit path.
500///
501/// Submission validation needs random slot lookup, but the queue must not retain guest pointers
502/// after `submit` returns, including on rejection. The guard makes that property independent of
503/// every `?` in the admission and native-binding phases.
504struct PointerSlots<'a> {
505    slots: RefMut<'a, Vec<*mut c_void>>,
506}
507
508impl Deref for PointerSlots<'_> {
509    type Target = Vec<*mut c_void>;
510
511    fn deref(&self) -> &Self::Target {
512        &self.slots
513    }
514}
515
516impl DerefMut for PointerSlots<'_> {
517    fn deref_mut(&mut self) -> &mut Self::Target {
518        &mut self.slots
519    }
520}
521
522impl Drop for PointerSlots<'_> {
523    fn drop(&mut self) {
524        self.slots.clear();
525    }
526}
527
528/// Owned `ov_model_t`; a short-lived reader artifact freed right after compilation.
529struct ModelHandle {
530    model: NonNull<ffi::ov_model_t>,
531}
532
533impl Drop for ModelHandle {
534    fn drop(&mut self) {
535        // SAFETY: this handle owns one model reference and is dropped exactly once.
536        unsafe { (ffi::api().ov_model_free)(self.model.as_ptr()) }
537    }
538}
539
540/// Owned `ov_compiled_model_t`.
541struct CompiledModelHandle {
542    compiled: NonNull<ffi::ov_compiled_model_t>,
543}
544
545impl CompiledModelHandle {
546    const fn as_const_ptr(&self) -> *const ffi::ov_compiled_model_t {
547        self.compiled.as_ptr()
548    }
549}
550
551impl Drop for CompiledModelHandle {
552    fn drop(&mut self) {
553        // SAFETY: this handle owns one compiled-model reference and is dropped exactly once.
554        unsafe { (ffi::api().ov_compiled_model_free)(self.compiled.as_ptr()) }
555    }
556}
557
558/// Read an IR document into a model, sharing the caller's weights memory when there is any.
559fn read_model(
560    core: &CoreHandle,
561    xml: &[u8],
562    weights: Option<&TensorHandle>,
563) -> Result<ModelHandle, BackendError> {
564    let mut model = ptr::null_mut();
565    // SAFETY: core, document bytes, and the (possibly null) weights tensor are live for this
566    // synchronous call; the created model shares the weights memory, which the caller keeps
567    // resident for as long as the model lives.
568    let status = unsafe {
569        (ffi::api().ov_core_read_model_from_memory_buffer)(
570            core.as_const_ptr(),
571            xml.as_ptr().cast(),
572            xml.len(),
573            weights.map_or(ptr::null(), TensorHandle::as_const_ptr),
574            &mut model,
575        )
576    };
577    check_status(status)?;
578    NonNull::new(model)
579        .map(|model| ModelHandle { model })
580        .ok_or(BackendError::External {
581            domain: OPENVINO_EXTERNAL_DOMAIN,
582            code: 0,
583        })
584}
585
586/// Whether this device's compiler accepts an FP8 graph, asked by compiling the smallest one.
587///
588/// Advertised capability has to be true of the device in hand, not of the backend in general.
589/// Intel NPU arch 5010 (Panther Lake) compiles FP8; arch 40XX (Lunar Lake) refuses even an FP8
590/// `IDENTITY`, and the FP8 handling in the driver-side compiler's own tree is arch-gated. There
591/// is no property to read for this -- `OPTIMIZATION_CAPABILITIES` omits FP8 on 5010, where it
592/// works -- so the tier is probed rather than branded, and a driver that gains FP8 later starts
593/// advertising it here with no allowlist to edit.
594fn device_accepts_fp8(core: &CoreHandle, device: &CStr) -> bool {
595    let probe = crate::lower::fp8_probe_document();
596    let Ok(model) = read_model(core, &probe.xml, None) else {
597        return false;
598    };
599    let accepted = compile_with_accuracy(core, &model, device).is_ok();
600    drop(model);
601    accepted
602}
603
604fn device_accepts_quantized_fp32(core: &CoreHandle, device: &CStr) -> bool {
605    let probe = crate::lower::fp32_probe_document();
606    let Ok(model) = read_model(core, &probe.xml, None) else {
607        return false;
608    };
609    compile_with_precision(core, &model, device, true).is_ok()
610}
611
612/// Compile existing native tiers with the ACCURACY hint. Quantized FP32 paths use
613/// `compile_with_precision` because the hint alone does not guarantee FP32 on every plugin.
614fn compile_with_accuracy(
615    core: &CoreHandle,
616    model: &ModelHandle,
617    device: &CStr,
618) -> Result<CompiledModelHandle, BackendError> {
619    compile_with_precision(core, model, device, false)
620}
621
622fn compile_with_precision(
623    core: &CoreHandle,
624    model: &ModelHandle,
625    device: &CStr,
626    fp32: bool,
627) -> Result<CompiledModelHandle, BackendError> {
628    let mut compiled = ptr::null_mut();
629    let disable_dynamic_quantization =
630        device.to_bytes().starts_with(b"CPU") || device.to_bytes().starts_with(b"GPU");
631    // SAFETY: core, model, and device are live; `property_args_size` counts the variadic
632    // arguments (one key/value pair contributes two) per the documented convention pinned by a
633    // unit test. All keys/values are static C strings (or the retained runtime key).
634    // CPU/GPU otherwise insert lossy activation quantization for compressed weights,
635    // even with ACCURACY. NPU does not expose this property. Optional pairs form a
636    // contiguous prefix, with the count matching exactly; all pointers outlive the call.
637    let status = unsafe {
638        (ffi::api().ov_core_compile_model)(
639            core.as_const_ptr(),
640            model.model.as_ptr(),
641            device.as_ptr(),
642            2 + 2 * usize::from(disable_dynamic_quantization) + 2 * usize::from(fp32),
643            &mut compiled,
644            ffi::execution_mode_property(),
645            c"ACCURACY".as_ptr(),
646            if disable_dynamic_quantization {
647                c"DYNAMIC_QUANTIZATION_GROUP_SIZE".as_ptr()
648            } else {
649                c"INFERENCE_PRECISION_HINT".as_ptr()
650            },
651            if disable_dynamic_quantization {
652                c"0".as_ptr()
653            } else {
654                c"f32".as_ptr()
655            },
656            c"INFERENCE_PRECISION_HINT".as_ptr(),
657            c"f32".as_ptr(),
658        )
659    };
660    check_status(status)?;
661    NonNull::new(compiled)
662        .map(|compiled| CompiledModelHandle { compiled })
663        .ok_or(BackendError::External {
664            domain: OPENVINO_EXTERNAL_DOMAIN,
665            code: 0,
666        })
667}
668
669const fn element_code(element: OvElement) -> ffi::ov_element_type_e {
670    match element {
671        OvElement::F32 => ffi::ELEMENT_F32,
672        OvElement::F16 => ffi::ELEMENT_F16,
673        OvElement::F8E4M3 => ffi::ELEMENT_F8E4M3,
674        OvElement::F8E5M2 => ffi::ELEMENT_F8E5M2,
675        OvElement::I8 => ffi::ELEMENT_I8,
676        OvElement::I4 => panic!("i4 is internal constant storage, never a boundary tensor"),
677        OvElement::I32 => ffi::ELEMENT_I32,
678        OvElement::I64 => ffi::ELEMENT_I64,
679        OvElement::Bool => ffi::ELEMENT_BOOLEAN,
680    }
681}
682
683/// One binding slot of a loaded program.
684struct SlotPlan {
685    slot: u32,
686    access: u8,
687    role: LoweredFeatureRole,
688    io_index: usize,
689    element: ffi::ov_element_type_e,
690    scalar_bytes: u64,
691    byte_len: u64,
692    shape: OwnedShape,
693}
694
695fn build_slot_plan(features: &[LoweredFeature]) -> Result<Vec<SlotPlan>, BackendError> {
696    let mut slots = Vec::new();
697    slots
698        .try_reserve_exact(features.len())
699        .map_err(|_| BackendError::OutOfMemory)?;
700    for feature in features {
701        slots.push(SlotPlan {
702            slot: feature.slot,
703            access: match feature.role {
704                LoweredFeatureRole::Input => AccessMode::Read as u8,
705                LoweredFeatureRole::Output => AccessMode::Write as u8,
706            },
707            role: feature.role,
708            io_index: feature.io_index as usize,
709            element: element_code(feature.element),
710            scalar_bytes: u64::from(feature.element.scalar_bytes()),
711            byte_len: feature.byte_len,
712            shape: OwnedShape::new(&feature.dims)?,
713        });
714    }
715    debug_assert!(slots.is_sorted_by_key(|plan| plan.slot));
716    Ok(slots)
717}
718
719/// Whether an enumerated device name satisfies a requested name or class prefix.
720///
721/// `"GPU"` matches `"GPU"` and indexed instances such as `"GPU.1"`, but never `"GPUX"`.
722fn matches_device(available: &str, requested: &str) -> bool {
723    match available.as_bytes().get(requested.len()) {
724        None => available == requested,
725        Some(b'.') => available.starts_with(requested),
726        Some(_) => false,
727    }
728}
729
730fn device_info_for(device: &str) -> DeviceInfo {
731    let class = if device.starts_with("NPU") {
732        AcceleratorClass::NPU
733    } else if device.starts_with("GPU") {
734        AcceleratorClass::GPU
735    } else {
736        AcceleratorClass::OTHER
737    };
738    let mut uuid = *b"intel-ov-\0\0\0\0\0\0\0";
739    for (slot, byte) in uuid[9..].iter_mut().zip(device.bytes()) {
740        *slot = byte.to_ascii_lowercase();
741    }
742    DeviceInfo {
743        identity: DeviceIdentity {
744            uuid,
745            class,
746            vendor_id: 0x8086,
747            device_id: 0,
748        },
749        capabilities: Capabilities::HOST_VISIBLE_MEMORY | Capabilities::SHARED_MEMORY,
750        limits: DeviceLimits {
751            max_contexts: 64,
752            max_buffers_per_context: 1_024,
753            max_programs_per_context: 64,
754            max_queues_per_context: 64,
755            max_events_per_context: 4_096,
756            max_bindings_per_submission: 256,
757            max_buffer_bytes: 16 * 1024 * 1024 * 1024,
758            max_artifact_bytes: MAX_TOSA_ARTIFACT_BYTES,
759        },
760    }
761}
762
763/// OpenVINO context handle.
764#[derive(Debug)]
765pub struct OpenVinoContext {
766    id: u64,
767}
768
769/// Page-aligned buffer directly wrapped by OpenVINO tensors.
770#[derive(Debug)]
771pub struct OpenVinoBuffer {
772    context_id: u64,
773    desc: BufferDesc,
774    allocation: Arc<AlignedAllocation>,
775    _not_send_sync: PhantomData<Rc<()>>,
776}
777
778/// Resident compiled OpenVINO model.
779pub struct OpenVinoProgram {
780    context_id: u64,
781    compiled: CompiledModelHandle,
782    slots: Vec<SlotPlan>,
783    /// The reader shares the weights memory; both stay resident for the program lifetime
784    /// because plugin retention of shared constants is unspecified.
785    _weights_tensor: Option<TensorHandle>,
786    _weights: Vec<u8>,
787    _not_send_sync: PhantomData<Rc<()>>,
788}
789
790impl std::fmt::Debug for OpenVinoProgram {
791    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792        formatter
793            .debug_struct("OpenVinoProgram")
794            .field("context_id", &self.context_id)
795            .finish_non_exhaustive()
796    }
797}
798
799/// OpenVINO execution queue handle with reusable per-submission scratch.
800#[derive(Debug)]
801pub struct OpenVinoQueue {
802    context_id: u64,
803    scratch: Rc<QueueScratch>,
804}
805
806/// Asynchronous OpenVINO inference event.
807///
808/// Owns the infer request, the bound tensors, and the buffer in-flight guards. The first
809/// observed terminal state is latched; the guards are dropped strictly before the latch is
810/// published.
811pub struct OpenVinoEvent {
812    request: NonNull<ffi::ov_infer_request_t>,
813    metadata: RefCell<EventMetadata>,
814    scratch: Weak<QueueScratch>,
815    latched: Cell<Option<EventState>>,
816    deadline: Option<Instant>,
817    cancel_issued: Cell<bool>,
818    _not_send_sync: PhantomData<Rc<()>>,
819}
820
821impl std::fmt::Debug for OpenVinoEvent {
822    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823        formatter
824            .debug_struct("OpenVinoEvent")
825            .field("latched", &self.latched.get())
826            .finish_non_exhaustive()
827    }
828}
829
830impl OpenVinoEvent {
831    /// Publish the first observed terminal state; guard release precedes latch publication so a
832    /// caller observing a terminal state can immediately transfer buffer bytes.
833    fn latch(&self, state: EventState) -> EventState {
834        self.metadata.borrow_mut().backings.clear();
835        self.latched.set(Some(state));
836        state
837    }
838
839    fn recycle_metadata(&self) {
840        let mut metadata = self.metadata.borrow_mut();
841        if metadata.tensors.capacity() == 0 && metadata.backings.capacity() == 0 {
842            return;
843        }
844        metadata.tensors.clear();
845        metadata.backings.clear();
846        let returned = mem::take(&mut *metadata);
847        drop(metadata);
848        if let Some(scratch) = self.scratch.upgrade() {
849            scratch.recycle_metadata(returned);
850        }
851    }
852
853    /// Verify the runtime executed into the caller's own output allocations.
854    fn outputs_are_directly_backed(&self) -> Result<bool, BackendError> {
855        let metadata = self.metadata.borrow();
856        for bound in &metadata.tensors {
857            if bound.expected_output.is_null() {
858                continue;
859            }
860            let mut tensor = ptr::null_mut();
861            // SAFETY: the request is live; the runtime returns one owned tensor reference.
862            check_status(unsafe {
863                (ffi::api().ov_infer_request_get_output_tensor_by_index)(
864                    self.request.as_ptr(),
865                    bound.output_io_index,
866                    &mut tensor,
867                )
868            })?;
869            let tensor = NonNull::new(tensor).ok_or(BackendError::External {
870                domain: OPENVINO_EXTERNAL_DOMAIN,
871                code: 0,
872            })?;
873            let probe = TensorHandle { tensor };
874            let mut data = ptr::null_mut();
875            // SAFETY: the probe tensor is live and `data` is a valid out-pointer.
876            check_status(unsafe { (ffi::api().ov_tensor_data)(probe.as_const_ptr(), &mut data) })?;
877            if data != bound.expected_output {
878                return Ok(false);
879            }
880        }
881        Ok(true)
882    }
883}
884
885impl Drop for OpenVinoEvent {
886    fn drop(&mut self) {
887        if self.latched.get().is_none() {
888            // The inference may still be running and writing through the bound tensors into
889            // allocations this drop is about to release: cancel best-effort, then block until
890            // the request is terminal before freeing anything.
891            // SAFETY: the request is live; cancel and wait are ordinary request entry points and
892            // their statuses are deliberately ignored (any terminal outcome suffices).
893            unsafe {
894                let _ = (ffi::api().ov_infer_request_cancel)(self.request.as_ptr());
895                let _ = (ffi::api().ov_infer_request_wait)(self.request.as_ptr());
896            }
897        }
898        // SAFETY: this handle owns the request reference and frees it exactly once; the bound
899        // tensors are dropped only after this call, then the already-terminal backing guards are
900        // released. This ordering also applies to a pre-start rejection.
901        unsafe { (ffi::api().ov_infer_request_free)(self.request.as_ptr()) };
902        self.recycle_metadata();
903    }
904}
905
906/// Intel OpenVINO backend instance bound to one inference device.
907pub struct OpenVinoAccelerator {
908    core: Arc<CoreHandle>,
909    device: CString,
910    next_id: AtomicU64,
911    direct_binding_admissions: AtomicU64,
912    explicit_transfer_bytes: AtomicU64,
913    info: DeviceInfo,
914    /// Whether this device's compiler accepts FP8, probed once at open.
915    fp8: bool,
916    quantized_fp32: bool,
917}
918
919impl std::fmt::Debug for OpenVinoAccelerator {
920    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
921        formatter
922            .debug_struct("OpenVinoAccelerator")
923            .field("device", &self.device_name())
924            .finish_non_exhaustive()
925    }
926}
927
928impl OpenVinoAccelerator {
929    /// Initialize runtime loading from an installed library (for example a Python
930    /// OpenVINO wheel). The first successful load is retained for the process
931    /// lifetime. Call before discovery; this never replaces an active runtime.
932    #[cfg(feature = "runtime-loading")]
933    pub fn load_runtime_from(path: &std::path::Path) -> Result<(), InitError> {
934        ffi::load_from(path)
935    }
936
937    /// Enumerate concrete runtime endpoints without choosing a default device.
938    pub fn available_devices() -> Result<Vec<String>, InitError> {
939        shared_core()?.available_devices()
940    }
941
942    /// Open the preferred available inference device: NPU, then GPU, then CPU.
943    pub fn new() -> Result<Self, InitError> {
944        let core = shared_core()?;
945        let devices = core.available_devices()?;
946        let device = ["NPU", "GPU", "CPU"]
947            .into_iter()
948            .find_map(|preferred| {
949                devices
950                    .iter()
951                    .find(|available| matches_device(available, preferred))
952            })
953            .cloned()
954            .ok_or(InitError::DeviceUnavailable)?;
955        Self::with_selected(core, device)
956    }
957
958    /// Open one specific device, by enumerated name (`"GPU.1"`) or class prefix (`"NPU"`).
959    pub fn with_device(device: &str) -> Result<Self, InitError> {
960        let core = shared_core()?;
961        let devices = core.available_devices()?;
962        // An enumerated endpoint must win over a class-prefix match.
963        let resolved = devices
964            .iter()
965            .find(|available| available.as_str() == device)
966            .or_else(|| {
967                devices
968                    .iter()
969                    .find(|available| matches_device(available, device))
970            })
971            .cloned()
972            .ok_or(InitError::DeviceUnavailable)?;
973        Self::with_selected(core, resolved)
974    }
975
976    fn with_selected(core: Arc<CoreHandle>, device: String) -> Result<Self, InitError> {
977        let info = device_info_for(&device);
978        let device = CString::new(device).map_err(|_| InitError::DeviceUnavailable)?;
979        let fp8 = device_accepts_fp8(&core, &device);
980        let quantized_fp32 = device_accepts_quantized_fp32(&core, &device);
981        Ok(Self {
982            core,
983            device,
984            next_id: AtomicU64::new(0),
985            direct_binding_admissions: AtomicU64::new(0),
986            explicit_transfer_bytes: AtomicU64::new(0),
987            info,
988            fp8,
989            quantized_fp32,
990        })
991    }
992
993    /// Whether this instance advertises the FP8 tier, which depends on the device it opened.
994    pub fn advertises_fp8(&self) -> bool {
995        self.fp8
996    }
997
998    /// The enumerated name of the device this instance executes on.
999    /// The runtime's build number (`ov_get_openvino_version`), the version a captured compiled
1000    /// blob must be bound to.
1001    pub fn runtime_version() -> Result<String, InitError> {
1002        ffi::ensure_loaded()?;
1003        let mut version = ffi::ov_version_t {
1004            build_number: ptr::null(),
1005            description: ptr::null(),
1006        };
1007        // SAFETY: `version` is a valid out-structure; on success the runtime owns both strings
1008        // until `ov_version_free`, and they are copied before that release.
1009        unsafe {
1010            if (ffi::api().ov_get_openvino_version)(&mut version) != ffi::OV_STATUS_OK
1011                || version.build_number.is_null()
1012            {
1013                return Err(InitError::RuntimeUnavailable);
1014            }
1015            let build = CStr::from_ptr(version.build_number)
1016                .to_string_lossy()
1017                .into_owned();
1018            (ffi::api().ov_version_free)(&mut version);
1019            Ok(build)
1020        }
1021    }
1022
1023    /// Export the plugin-compiled form of `program` to `path` through
1024    /// `ov_compiled_model_export_model`: the NPU plugin writes its VPUX ELF, the GPU plugin its
1025    /// serialized graph with the OpenCL program binaries (Intel GT zebin ELFs) embedded. The
1026    /// bytes are the runtime's own export format for this device and OpenVINO version; a
1027    /// consumer that keeps them must bind them to the artifact and version that produced them.
1028    /// The program stays loaded and usable afterwards.
1029    pub fn export_program(
1030        &self,
1031        program: &OpenVinoProgram,
1032        path: &std::path::Path,
1033    ) -> Result<(), BackendError> {
1034        let path = CString::new(path.as_os_str().as_encoded_bytes())
1035            .map_err(|_| BackendError::InvalidArgument)?;
1036        // SAFETY: the compiled model is live for the program's lifetime and `path` is a valid
1037        // NUL-terminated string for the duration of the call.
1038        unsafe {
1039            check_status((ffi::api().ov_compiled_model_export_model)(
1040                program.compiled.as_const_ptr(),
1041                path.as_ptr(),
1042            ))
1043        }
1044    }
1045
1046    pub fn device_name(&self) -> &str {
1047        self.device.to_str().unwrap_or_default()
1048    }
1049
1050    /// Re-enumerate inference devices through this instance's runtime core.
1051    pub fn runtime_devices(&self) -> Result<Vec<String>, InitError> {
1052        self.core.available_devices()
1053    }
1054
1055    /// Cumulative count of buffers admitted as direct bindings.
1056    pub fn direct_binding_admissions(&self) -> u64 {
1057        self.direct_binding_admissions.load(Ordering::Relaxed)
1058    }
1059
1060    /// Cumulative bytes moved by explicit `write_buffer`/`read_buffer` transfers.
1061    pub fn explicit_transfer_bytes(&self) -> u64 {
1062        self.explicit_transfer_bytes.load(Ordering::Relaxed)
1063    }
1064
1065    fn next_id(&self) -> Result<u64, BackendError> {
1066        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
1067        if id == u64::MAX {
1068            return Err(BackendError::ResourceLimit);
1069        }
1070        Ok(id)
1071    }
1072
1073    fn checked_range(
1074        buffer: &OpenVinoBuffer,
1075        offset: u64,
1076        bytes: u64,
1077    ) -> Result<(usize, usize), BackendError> {
1078        if bytes == 0 {
1079            return Err(BackendError::InvalidArgument);
1080        }
1081        let end = offset
1082            .checked_add(bytes)
1083            .filter(|end| *end <= buffer.desc.bytes())
1084            .ok_or(BackendError::OutOfBounds)?;
1085        let start = usize::try_from(offset).map_err(|_| BackendError::OutOfBounds)?;
1086        let end = usize::try_from(end).map_err(|_| BackendError::OutOfBounds)?;
1087        Ok((start, end))
1088    }
1089
1090    fn lowering_error(error: crate::LoweringError) -> BackendError {
1091        match error {
1092            crate::LoweringError::Parse(_)
1093            | crate::LoweringError::Analysis(_)
1094            | crate::LoweringError::InvalidConstant => BackendError::InvalidArgument,
1095            crate::LoweringError::UnsupportedGraph
1096            | crate::LoweringError::UnsupportedType(_)
1097            | crate::LoweringError::UnsupportedOperator(_) => BackendError::Unsupported,
1098            crate::LoweringError::ResourceLimit => BackendError::ResourceLimit,
1099        }
1100    }
1101
1102    /// Probe a live request without blocking and latch any terminal state.
1103    fn poll_request(&self, event: &OpenVinoEvent) -> EventState {
1104        if let Some(state) = event.latched.get() {
1105            return state;
1106        }
1107        // SAFETY: the request is live; a zero timeout is a non-blocking readiness probe.
1108        let mut status =
1109            unsafe { (ffi::api().ov_infer_request_wait_for)(event.request.as_ptr(), 0) };
1110        if status == ffi::OV_STATUS_RESULT_NOT_READY {
1111            let expired = event
1112                .deadline
1113                .is_some_and(|deadline| Instant::now() >= deadline);
1114            if !expired || event.cancel_issued.get() {
1115                return EventState::Pending;
1116            }
1117            event.cancel_issued.set(true);
1118            // SAFETY: cancel on a live request; the follow-up probe observes the outcome.
1119            unsafe {
1120                let _ = (ffi::api().ov_infer_request_cancel)(event.request.as_ptr());
1121                status = (ffi::api().ov_infer_request_wait_for)(event.request.as_ptr(), 0);
1122            }
1123            if status == ffi::OV_STATUS_RESULT_NOT_READY {
1124                return EventState::Pending;
1125            }
1126        }
1127        let state = match status {
1128            ffi::OV_STATUS_OK => match event.outputs_are_directly_backed() {
1129                Ok(true) => EventState::Complete,
1130                // A provider-side output reallocation is an execution failure, never a hidden
1131                // copy back into the caller's binding.
1132                Ok(false) => EventState::Failed(BackendError::Incompatible),
1133                Err(error) => EventState::Failed(error),
1134            },
1135            ffi::OV_STATUS_INFER_CANCELLED if event.cancel_issued.get() => {
1136                EventState::Failed(BackendError::DeadlineExpired)
1137            }
1138            other => EventState::Failed(backend_error_from_status(other)),
1139        };
1140        event.latch(state)
1141    }
1142}
1143
1144impl TosaCapabilityProvider for OpenVinoAccelerator {
1145    fn tosa_capabilities(&self) -> &'static [CapabilityDescriptor] {
1146        match (self.fp8, self.quantized_fp32) {
1147            (true, true) => crate::TOSA_CAPABILITIES_WITH_FP8,
1148            (false, true) => crate::TOSA_CAPABILITIES,
1149            (true, false) => crate::TOSA_CAPABILITIES_FP16_WITH_FP8,
1150            (false, false) => crate::TOSA_CAPABILITIES_FP16,
1151        }
1152    }
1153}
1154
1155impl Accelerator for OpenVinoAccelerator {
1156    type Context = OpenVinoContext;
1157    type Buffer = OpenVinoBuffer;
1158    type Program = OpenVinoProgram;
1159    type Queue = OpenVinoQueue;
1160    type Event = OpenVinoEvent;
1161
1162    fn device_info(&self) -> Result<DeviceInfo, BackendError> {
1163        Ok(self.info)
1164    }
1165
1166    fn create_context(&self, desc: ContextDesc) -> Result<Self::Context, BackendError> {
1167        self.info.validate_context_desc(desc)?;
1168        Ok(OpenVinoContext {
1169            id: self.next_id()?,
1170        })
1171    }
1172
1173    fn destroy_context(
1174        &self,
1175        _context: Self::Context,
1176    ) -> Result<(), ReleaseFailure<Self::Context>> {
1177        Ok(())
1178    }
1179
1180    fn allocate_buffer(
1181        &self,
1182        context: &Self::Context,
1183        desc: BufferDesc,
1184    ) -> Result<AllocatedBuffer<Self::Buffer>, BackendError> {
1185        self.info.validate_buffer_desc(desc)?;
1186        let allocation = Arc::new(AlignedAllocation::new(desc.bytes(), desc.alignment())?);
1187        let properties = BufferProperties::HOST_VISIBLE
1188            | if desc.is_program_visible() || desc.domain == MemoryDomain::Shared {
1189                BufferProperties::DIRECT_BINDING
1190            } else {
1191                BufferProperties::empty()
1192            };
1193        let info = BufferInfo::new(
1194            desc,
1195            allocation.allocation_bytes(),
1196            allocation.alignment(),
1197            properties,
1198        )?;
1199        Ok(AllocatedBuffer::new(
1200            OpenVinoBuffer {
1201                context_id: context.id,
1202                desc,
1203                allocation,
1204                _not_send_sync: PhantomData,
1205            },
1206            info,
1207        ))
1208    }
1209
1210    fn write_buffer(
1211        &self,
1212        buffer: &mut Self::Buffer,
1213        offset: u64,
1214        data: &dyn ByteSource,
1215    ) -> Result<(), BackendError> {
1216        if !buffer
1217            .desc
1218            .usage
1219            .contains(BufferUsage::TRANSFER_DESTINATION)
1220        {
1221            return Err(BackendError::PermissionDenied);
1222        }
1223        if buffer.allocation.in_flight.load(Ordering::Acquire) != 0 {
1224            return Err(BackendError::Busy);
1225        }
1226        let (start, end) = Self::checked_range(buffer, offset, data.len())?;
1227        let target_len = end - start;
1228        if let Some(source) = data.as_contiguous() {
1229            if source.len() != target_len {
1230                return Err(BackendError::InvalidArgument);
1231            }
1232            // SAFETY: the validated range lies within the owned allocation, `buffer` is
1233            // exclusively borrowed, and the source is a distinct borrowed byte region.
1234            unsafe {
1235                std::ptr::copy_nonoverlapping(
1236                    source.as_ptr(),
1237                    buffer.allocation.pointer_at(start),
1238                    target_len,
1239                )
1240            };
1241            self.explicit_transfer_bytes
1242                .fetch_add(target_len as u64, Ordering::Relaxed);
1243            return Ok(());
1244        }
1245
1246        let mut scratch = [0; TRANSFER_CHUNK_BYTES];
1247        let mut copied = 0usize;
1248        while copied < target_len {
1249            let chunk = (target_len - copied).min(scratch.as_slice().len());
1250            data.read_at(copied as u64, &mut scratch[..chunk])?;
1251            // SAFETY: `start + copied .. + chunk` stays inside the validated exclusive range.
1252            unsafe {
1253                std::ptr::copy_nonoverlapping(
1254                    scratch.as_ptr(),
1255                    buffer.allocation.pointer_at(start + copied),
1256                    chunk,
1257                )
1258            };
1259            self.explicit_transfer_bytes
1260                .fetch_add(chunk as u64, Ordering::Relaxed);
1261            copied += chunk;
1262        }
1263        Ok(())
1264    }
1265
1266    fn read_buffer(
1267        &self,
1268        buffer: &Self::Buffer,
1269        offset: u64,
1270        data: &mut dyn ByteSink,
1271    ) -> Result<(), BackendError> {
1272        if !buffer.desc.usage.contains(BufferUsage::TRANSFER_SOURCE) {
1273            return Err(BackendError::PermissionDenied);
1274        }
1275        if buffer.allocation.in_flight.load(Ordering::Acquire) != 0 {
1276            return Err(BackendError::Busy);
1277        }
1278        let (start, end) = Self::checked_range(buffer, offset, data.len())?;
1279        let source_len = end - start;
1280        if let Some(target) = data.as_contiguous_mut() {
1281            if target.len() != source_len {
1282                return Err(BackendError::InvalidArgument);
1283            }
1284            // SAFETY: the source range is validated and the in-flight gate proved that no native
1285            // inference still mutates this buffer.
1286            unsafe {
1287                std::ptr::copy_nonoverlapping(
1288                    buffer.allocation.pointer_at(start),
1289                    target.as_mut_ptr(),
1290                    source_len,
1291                )
1292            };
1293            self.explicit_transfer_bytes
1294                .fetch_add(source_len as u64, Ordering::Relaxed);
1295            return Ok(());
1296        }
1297
1298        let mut scratch = [0; TRANSFER_CHUNK_BYTES];
1299        let mut copied = 0usize;
1300        while copied < source_len {
1301            let chunk = (source_len - copied).min(scratch.as_slice().len());
1302            // SAFETY: `start + copied .. + chunk` remains in the validated source range.
1303            unsafe {
1304                std::ptr::copy_nonoverlapping(
1305                    buffer.allocation.pointer_at(start + copied),
1306                    scratch.as_mut_ptr(),
1307                    chunk,
1308                )
1309            };
1310            data.write_at(copied as u64, &scratch[..chunk])?;
1311            self.explicit_transfer_bytes
1312                .fetch_add(chunk as u64, Ordering::Relaxed);
1313            copied += chunk;
1314        }
1315        Ok(())
1316    }
1317
1318    fn free_buffer(&self, _buffer: Self::Buffer) -> Result<(), ReleaseFailure<Self::Buffer>> {
1319        Ok(())
1320    }
1321
1322    fn load_program(
1323        &self,
1324        context: &Self::Context,
1325        artifact: ArtifactRef<'_>,
1326    ) -> Result<Self::Program, BackendError> {
1327        if artifact.payload.len() > self.info.limits.max_artifact_bytes {
1328            return Err(BackendError::ResourceLimit);
1329        }
1330        if artifact.resident_bytes != REQUIRED_RESIDENT_BYTES {
1331            return Err(BackendError::ResourceLimit);
1332        }
1333        if artifact.format != virtio_accel_tosa::ARTIFACT_FORMAT {
1334            return Err(BackendError::Unsupported);
1335        }
1336        let target = virtio_accel_tosa::Target::from_identity(artifact.target)
1337            .map_err(|_| BackendError::Incompatible)?;
1338        let mut owned = Vec::new();
1339        let bytes = match artifact.payload.as_contiguous() {
1340            Some(bytes) => bytes,
1341            None => {
1342                let len = usize::try_from(artifact.payload.len())
1343                    .map_err(|_| BackendError::ResourceLimit)?;
1344                owned
1345                    .try_reserve_exact(len)
1346                    .map_err(|_| BackendError::OutOfMemory)?;
1347                owned.resize(len, 0);
1348                artifact.payload.read_at(0, &mut owned)?;
1349                &owned
1350            }
1351        };
1352        // GPU's compressed kernel preserves the explicit FP16 dequantization.
1353        // CPU avoids per-inference expansion; NPU needs a materialized rounded
1354        // constant to prevent scale fusion from changing FP16 intermediates.
1355        let expand_weights = self.device.to_bytes().starts_with(b"CPU")
1356            || self.device.to_bytes().starts_with(b"NPU");
1357        let lowered =
1358            lower_tosa_with_weights(bytes, target, expand_weights).map_err(Self::lowering_error)?;
1359        let require_fp32 = (target == crate::OPENVINO_TOSA_QUANTIZED_TARGET
1360            || target == crate::OPENVINO_TOSA_FP8_TARGET)
1361            && lowered.requires_fp32;
1362        if require_fp32 && !self.quantized_fp32 {
1363            return Err(BackendError::Unsupported);
1364        }
1365        let slots = build_slot_plan(&lowered.features)?;
1366        let inputs = lowered
1367            .features
1368            .iter()
1369            .filter(|feature| feature.role == LoweredFeatureRole::Input)
1370            .count();
1371        let outputs = lowered.features.len() - inputs;
1372
1373        let weights_tensor = if lowered.weights.is_empty() {
1374            None
1375        } else {
1376            let shape = OwnedShape::new(&[lowered.weights.len() as i64])?;
1377            Some(TensorHandle::from_host_ptr(
1378                ffi::ELEMENT_U8,
1379                shape.as_value(),
1380                lowered.weights.as_ptr().cast_mut().cast(),
1381            )?)
1382        };
1383
1384        let model = read_model(&self.core, &lowered.xml, weights_tensor.as_ref())?;
1385        let compiled = compile_with_precision(&self.core, &model, &self.device, require_fp32)?;
1386        drop(model);
1387
1388        // Emission order defined the model I/O indices; verify the compiled counts agree before
1389        // trusting any `*_by_index` call.
1390        let (mut model_inputs, mut model_outputs) = (0usize, 0usize);
1391        // SAFETY: the compiled model is live and the out-pointers are valid.
1392        unsafe {
1393            check_status((ffi::api().ov_compiled_model_inputs_size)(
1394                compiled.as_const_ptr(),
1395                &mut model_inputs,
1396            ))?;
1397            check_status((ffi::api().ov_compiled_model_outputs_size)(
1398                compiled.as_const_ptr(),
1399                &mut model_outputs,
1400            ))?;
1401        }
1402        if (model_inputs, model_outputs) != (inputs, outputs) {
1403            return Err(BackendError::Incompatible);
1404        }
1405
1406        Ok(OpenVinoProgram {
1407            context_id: context.id,
1408            compiled,
1409            slots,
1410            _weights_tensor: weights_tensor,
1411            _weights: lowered.weights,
1412            _not_send_sync: PhantomData,
1413        })
1414    }
1415
1416    fn unload_program(&self, _program: Self::Program) -> Result<(), ReleaseFailure<Self::Program>> {
1417        Ok(())
1418    }
1419
1420    fn create_queue(
1421        &self,
1422        context: &Self::Context,
1423        desc: QueueDesc,
1424    ) -> Result<Self::Queue, BackendError> {
1425        self.info.validate_queue_desc(desc)?;
1426        Ok(OpenVinoQueue {
1427            context_id: context.id,
1428            scratch: Rc::new(QueueScratch::default()),
1429        })
1430    }
1431
1432    fn destroy_queue(&self, _queue: Self::Queue) -> Result<(), ReleaseFailure<Self::Queue>> {
1433        Ok(())
1434    }
1435
1436    fn submit(
1437        &self,
1438        queue: &Self::Queue,
1439        program: &Self::Program,
1440        bindings: &[BindingRef<'_, Self::Buffer>],
1441        timeout: Timeout,
1442    ) -> Result<Self::Event, SubmitFailure<Self::Event>> {
1443        if bindings.is_empty()
1444            || bindings.len() > self.info.limits.max_bindings_per_submission as usize
1445        {
1446            return Err(SubmitFailure::Rejected(BackendError::ResourceLimit));
1447        }
1448        if queue.context_id != program.context_id {
1449            return Err(SubmitFailure::Rejected(BackendError::InvalidArgument));
1450        }
1451        let mut pointers = queue
1452            .scratch
1453            .take_pointer_slots(program.slots.len())
1454            .map_err(SubmitFailure::Rejected)?;
1455        let mut event_metadata = queue
1456            .scratch
1457            .take_metadata(bindings.len(), program.slots.len())
1458            .map_err(SubmitFailure::Rejected)?;
1459        let mut seen = [0_u64; 4];
1460        for binding in bindings {
1461            if binding.buffer.context_id != queue.context_id {
1462                return Err(SubmitFailure::Rejected(BackendError::InvalidArgument));
1463            }
1464            if !binding.buffer.desc.allows_access(binding.access) {
1465                return Err(SubmitFailure::Rejected(BackendError::PermissionDenied));
1466            }
1467            let (start, _) =
1468                Self::checked_range(binding.buffer, binding.range.offset, binding.range.bytes())
1469                    .map_err(SubmitFailure::Rejected)?;
1470            let index = program
1471                .slots
1472                .binary_search_by_key(&binding.slot, |slot| slot.slot)
1473                .map_err(|_| SubmitFailure::Rejected(BackendError::Incompatible))?;
1474            let bit = 1_u64 << (index % 64);
1475            if seen[index / 64] & bit != 0 {
1476                return Err(SubmitFailure::Rejected(BackendError::InvalidArgument));
1477            }
1478            seen[index / 64] |= bit;
1479            let plan = &program.slots[index];
1480            if binding.access as u8 != plan.access {
1481                return Err(SubmitFailure::Rejected(BackendError::Incompatible));
1482            }
1483            // The tensor wraps the range directly: it must cover the exact tensor bytes and be
1484            // scalar-aligned (the base allocation is page-aligned, so the offset decides).
1485            if binding.range.bytes() != plan.byte_len || start as u64 % plan.scalar_bytes != 0 {
1486                return Err(SubmitFailure::Rejected(BackendError::Incompatible));
1487            }
1488            pointers[index] = binding.buffer.allocation.pointer_at(start).cast();
1489            event_metadata.backings.push(EventBacking::new(
1490                Arc::clone(&binding.buffer.allocation),
1491                binding.access,
1492            ));
1493        }
1494        if bindings.len() != program.slots.len() {
1495            return Err(SubmitFailure::Rejected(BackendError::Incompatible));
1496        }
1497
1498        prepare_event_backings(&mut event_metadata.backings).map_err(SubmitFailure::Rejected)?;
1499
1500        // Native phase. Failures below free every created handle and reject: nothing observable
1501        // was started until `start_async` succeeds, so `SubmitFailure::Indeterminate` is never
1502        // produced.
1503        let mut request = ptr::null_mut();
1504        // SAFETY: the compiled model is live and `request` is a valid out-pointer.
1505        let status = unsafe {
1506            (ffi::api().ov_compiled_model_create_infer_request)(
1507                program.compiled.as_const_ptr(),
1508                &mut request,
1509            )
1510        };
1511        check_status(status).map_err(SubmitFailure::Rejected)?;
1512        let Some(request) = NonNull::new(request) else {
1513            return Err(SubmitFailure::Rejected(BackendError::External {
1514                domain: OPENVINO_EXTERNAL_DOMAIN,
1515                code: 0,
1516            }));
1517        };
1518        let event = OpenVinoEvent {
1519            request,
1520            metadata: RefCell::new(event_metadata),
1521            scratch: Rc::downgrade(&queue.scratch),
1522            // A pre-latched event never re-enters the runtime: on rejection below, `Drop` frees
1523            // the never-started request and tensors immediately.
1524            latched: Cell::new(Some(EventState::Failed(BackendError::InvalidArgument))),
1525            deadline: match timeout {
1526                Timeout::Infinite => None,
1527                Timeout::AfterNs(nanos) => {
1528                    Instant::now().checked_add(Duration::from_nanos(nanos.get()))
1529                }
1530            },
1531            cancel_issued: Cell::new(false),
1532            _not_send_sync: PhantomData,
1533        };
1534
1535        let mut metadata = event.metadata.borrow_mut();
1536        for (plan, data) in program.slots.iter().zip(pointers.iter()) {
1537            let tensor = TensorHandle::from_host_ptr(plan.element, plan.shape.as_value(), *data)
1538                .map_err(SubmitFailure::Rejected)?;
1539            // SAFETY: request and tensor are live; the runtime retains its own tensor reference.
1540            let status = unsafe {
1541                match plan.role {
1542                    LoweredFeatureRole::Input => (ffi::api()
1543                        .ov_infer_request_set_input_tensor_by_index)(
1544                        event.request.as_ptr(),
1545                        plan.io_index,
1546                        tensor.as_const_ptr(),
1547                    ),
1548                    LoweredFeatureRole::Output => (ffi::api()
1549                        .ov_infer_request_set_output_tensor_by_index)(
1550                        event.request.as_ptr(),
1551                        plan.io_index,
1552                        tensor.as_const_ptr(),
1553                    ),
1554                }
1555            };
1556            check_status(status).map_err(SubmitFailure::Rejected)?;
1557            metadata.tensors.push(BoundTensor {
1558                _tensor: tensor,
1559                output_io_index: plan.io_index,
1560                expected_output: if plan.role == LoweredFeatureRole::Output {
1561                    *data
1562                } else {
1563                    ptr::null_mut()
1564                },
1565            });
1566        }
1567        drop(metadata);
1568
1569        // SAFETY: the request is live with every boundary tensor bound.
1570        let status = unsafe { (ffi::api().ov_infer_request_start_async)(event.request.as_ptr()) };
1571        if status != ffi::OV_STATUS_OK {
1572            // Defense in depth: even though a failed start is specified not to have started,
1573            // join the request before the event drop releases the guards and tensors.
1574            // SAFETY: cancel and wait on a live request; statuses are deliberately ignored.
1575            unsafe {
1576                let _ = (ffi::api().ov_infer_request_cancel)(event.request.as_ptr());
1577                let _ = (ffi::api().ov_infer_request_wait)(event.request.as_ptr());
1578            }
1579            return Err(SubmitFailure::Rejected(backend_error_from_status(status)));
1580        }
1581        event.latched.set(None);
1582        self.direct_binding_admissions
1583            .fetch_add(bindings.len() as u64, Ordering::Relaxed);
1584        Ok(event)
1585    }
1586
1587    fn poll_event(&self, event: &Self::Event) -> Result<EventState, BackendError> {
1588        Ok(self.poll_request(event))
1589    }
1590
1591    fn destroy_event(&self, event: Self::Event) -> Result<(), ReleaseFailure<Self::Event>> {
1592        match self.poll_request(&event) {
1593            EventState::Pending => Err(ReleaseFailure::Rejected {
1594                error: BackendError::Busy,
1595                resource: event,
1596            }),
1597            EventState::Complete | EventState::Failed(_) | EventState::Cancelled => Ok(()),
1598        }
1599    }
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604    use super::*;
1605    use virtio_accel_conformance::numerics::{
1606        IDENTITY_EDGES_FP32, IDENTITY_FP8E4M3, IDENTITY_FP8E5M2, MATMUL_FP16, MATMUL_FP32,
1607        MAX_POOL2D_FP32,
1608    };
1609
1610    const IDENTITY_FP32_LOCAL: &[u8] = include_bytes!("../tests/data/identity-fp32-v1.0.0.tosa");
1611
1612    fn backend() -> Option<OpenVinoAccelerator> {
1613        match OpenVinoAccelerator::new() {
1614            Ok(backend) => Some(backend),
1615            Err(InitError::DeviceUnavailable | InitError::RuntimeUnavailable)
1616                if std::env::var("VIRTIO_ACCEL_OPENVINO_REQUIRE_HARDWARE").as_deref()
1617                    != Ok("1")
1618                    && std::env::var("VIRTIO_ACCEL_OPENVINO").as_deref() != Ok("1") =>
1619            {
1620                None
1621            }
1622            Err(error) => panic!("backend initialization failed: {error}"),
1623        }
1624    }
1625
1626    #[derive(Debug)]
1627    struct SliceSource<'a>(&'a [u8]);
1628
1629    impl ByteSource for SliceSource<'_> {
1630        fn len(&self) -> u64 {
1631            self.0.len() as u64
1632        }
1633
1634        fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), BackendError> {
1635            ByteSource::read_at(self.0, offset, target)
1636        }
1637
1638        fn as_contiguous(&self) -> Option<&[u8]> {
1639            Some(self.0)
1640        }
1641    }
1642
1643    #[derive(Debug)]
1644    struct SliceSink<'a>(&'a mut [u8]);
1645
1646    impl ByteSink for SliceSink<'_> {
1647        fn len(&self) -> u64 {
1648            self.0.len() as u64
1649        }
1650
1651        fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), BackendError> {
1652            ByteSink::write_at(self.0, offset, source)
1653        }
1654
1655        fn as_contiguous_mut(&mut self) -> Option<&mut [u8]> {
1656            Some(self.0)
1657        }
1658    }
1659
1660    fn tosa_artifact<'a>(payload: &'a SliceSource<'a>) -> ArtifactRef<'a> {
1661        tosa_artifact_for(payload, crate::OPENVINO_TOSA_TARGET)
1662    }
1663
1664    fn tosa_artifact_for<'a>(
1665        payload: &'a SliceSource<'a>,
1666        target: virtio_accel_tosa::Target,
1667    ) -> ArtifactRef<'a> {
1668        ArtifactRef {
1669            format: virtio_accel_tosa::ARTIFACT_FORMAT,
1670            target: target.to_identity(),
1671            payload,
1672            resident_bytes: REQUIRED_RESIDENT_BYTES,
1673        }
1674    }
1675
1676    fn wait_for_terminal(backend: &OpenVinoAccelerator, event: &OpenVinoEvent) -> EventState {
1677        let deadline = Instant::now() + Duration::from_secs(15);
1678        loop {
1679            match backend.poll_event(event).unwrap() {
1680                EventState::Pending => {
1681                    assert!(Instant::now() < deadline, "inference never completed");
1682                    std::thread::sleep(Duration::from_millis(1));
1683                }
1684                terminal => return terminal,
1685            }
1686        }
1687    }
1688
1689    #[test]
1690    fn device_matching_requires_exact_names_or_indexed_instances() {
1691        assert!(matches_device("NPU", "NPU"));
1692        assert!(matches_device("GPU.1", "GPU"));
1693        assert!(matches_device("GPU.1", "GPU.1"));
1694        assert!(!matches_device("GPUX", "GPU"));
1695        assert!(!matches_device("GPU", "GPU.1"));
1696        assert!(!matches_device("CPU", "GPU"));
1697    }
1698
1699    #[test]
1700    fn selects_a_device_and_reports_valid_stable_metadata() {
1701        let Some(backend) = backend() else { return };
1702        backend.device_info().unwrap().validate().unwrap();
1703        assert_eq!(backend.device_info(), backend.device_info());
1704        let name = backend.device_name().to_owned();
1705        assert!(!name.is_empty());
1706        assert!(backend.runtime_devices().unwrap().contains(&name));
1707    }
1708
1709    #[test]
1710    fn explicit_selection_resolves_every_enumerated_device() {
1711        let Some(backend) = backend() else { return };
1712        for device in backend.runtime_devices().unwrap() {
1713            let explicit = OpenVinoAccelerator::with_device(&device).unwrap();
1714            assert_eq!(explicit.device_name(), device);
1715            explicit.device_info().unwrap().validate().unwrap();
1716        }
1717        assert_eq!(
1718            OpenVinoAccelerator::with_device("no-such-device").unwrap_err(),
1719            InitError::DeviceUnavailable
1720        );
1721    }
1722
1723    #[test]
1724    fn native_backing_guard_allows_shared_users_and_excludes_writers() {
1725        let allocation = Arc::new(AlignedAllocation::new(32, 16).unwrap());
1726        let mut first = EventBacking::new(Arc::clone(&allocation), AccessMode::Read);
1727        first.acquire().unwrap();
1728        let mut second = EventBacking::new(Arc::clone(&allocation), AccessMode::Read);
1729        second.acquire().unwrap();
1730        let mut blocked_writer = EventBacking::new(Arc::clone(&allocation), AccessMode::Write);
1731        assert_eq!(blocked_writer.acquire().unwrap_err(), BackendError::Busy);
1732        drop(first);
1733        drop(second);
1734        let mut writer = EventBacking::new(Arc::clone(&allocation), AccessMode::ReadWrite);
1735        writer.acquire().unwrap();
1736        let mut blocked_reader = EventBacking::new(allocation, AccessMode::Read);
1737        assert_eq!(blocked_reader.acquire().unwrap_err(), BackendError::Busy);
1738        drop(writer);
1739    }
1740
1741    #[test]
1742    fn duplicate_allocation_access_collapses_to_exclusive() {
1743        let allocation = Arc::new(AlignedAllocation::new(32, 16).unwrap());
1744        let mut pending = vec![
1745            EventBacking::new(Arc::clone(&allocation), AccessMode::Read),
1746            EventBacking::new(allocation, AccessMode::Write),
1747        ];
1748        prepare_event_backings(&mut pending).unwrap();
1749        assert_eq!(pending.len(), 1);
1750        assert_eq!(pending[0].access, BackingAccess::Exclusive);
1751    }
1752
1753    #[test]
1754    fn queue_scratch_reuses_only_cleared_metadata_capacity() {
1755        let scratch = QueueScratch::default();
1756        let allocation = Arc::new(AlignedAllocation::new(32, 16).unwrap());
1757
1758        let mut metadata = scratch.take_metadata(2, 2).unwrap();
1759        let backing_storage = metadata.backings.as_ptr();
1760        let tensor_storage = metadata.tensors.as_ptr();
1761        metadata
1762            .backings
1763            .push(EventBacking::new(Arc::clone(&allocation), AccessMode::Read));
1764        assert_eq!(Arc::strong_count(&allocation), 2);
1765        scratch.recycle_metadata(metadata);
1766        assert_eq!(Arc::strong_count(&allocation), 1);
1767
1768        let reused = scratch.take_metadata(2, 2).unwrap();
1769        assert_eq!(reused.backings.as_ptr(), backing_storage);
1770        assert_eq!(reused.tensors.as_ptr(), tensor_storage);
1771        assert!(reused.backings.is_empty());
1772        assert!(reused.tensors.is_empty());
1773    }
1774
1775    #[test]
1776    fn pointer_scratch_is_scrubbed_on_every_exit() {
1777        let scratch = QueueScratch::default();
1778        {
1779            let mut slots = scratch.take_pointer_slots(2).unwrap();
1780            slots[0] = NonNull::<u8>::dangling().as_ptr().cast();
1781            slots[1] = NonNull::<u16>::dangling().as_ptr().cast();
1782        }
1783        assert!(scratch.pointer_slots.borrow().is_empty());
1784    }
1785
1786    /// Pins the runtime facts the lowering design depends on: in-memory IR v11 acceptance with a
1787    /// null weights tensor, a direct parameter-to-result edge, the variadic property convention
1788    /// of `ov_core_compile_model`, and index-stable I/O sizes — via the production load path.
1789    #[test]
1790    fn runtime_accepts_lowered_corpus_documents() {
1791        let Some(backend) = backend() else { return };
1792        let context = backend.create_context(ContextDesc::default()).unwrap();
1793        for (name, artifact) in [
1794            ("identity-fp32", IDENTITY_EDGES_FP32.artifact),
1795            ("matmul-fp32", MATMUL_FP32.artifact),
1796            ("max-pool2d-fp32", MAX_POOL2D_FP32.artifact),
1797            ("matmul-fp16", MATMUL_FP16.artifact),
1798        ] {
1799            let program = backend
1800                .load_program(&context, tosa_artifact(&SliceSource(artifact)))
1801                .unwrap_or_else(|error| panic!("{name}: load failed: {error:?}"));
1802            backend.unload_program(program).unwrap();
1803        }
1804        backend.destroy_context(context).unwrap();
1805    }
1806
1807    /// The milestone gate: a device-neutral TOSA identity executes end-to-end on the selected
1808    /// device with direct bindings only.
1809    #[test]
1810    fn fp8_tier_graphs_compile_on_the_device() {
1811        let Some(backend) = backend() else { return };
1812        eprintln!(
1813            "FP8 tier device: {} (FP8 advertised: {})",
1814            backend.device_name(),
1815            backend.advertises_fp8()
1816        );
1817        if !backend.advertises_fp8() {
1818            return;
1819        }
1820        let context = backend.create_context(ContextDesc::default()).unwrap();
1821        for dtype in [
1822            virtio_accel_tosa::DType::FP8E4M3,
1823            virtio_accel_tosa::DType::FP8E5M2,
1824        ] {
1825            for (name, artifact) in [
1826                ("matmul", crate::lower::fp8_matmul_graph(dtype)),
1827                ("max_pool2d", crate::lower::fp8_pool_graph(dtype)),
1828                ("transpose", crate::lower::fp8_transpose_graph(dtype)),
1829            ] {
1830                let program = backend
1831                    .load_program(
1832                        &context,
1833                        tosa_artifact_for(&SliceSource(&artifact), crate::OPENVINO_TOSA_FP8_TARGET),
1834                    )
1835                    .unwrap_or_else(|error| {
1836                        panic!("{dtype:?} {name}: device compilation failed: {error:?}")
1837                    });
1838                backend.unload_program(program).unwrap();
1839            }
1840        }
1841        backend.destroy_context(context).unwrap();
1842    }
1843
1844    /// Advertisement must match what the device will actually do, in both directions. A device
1845    /// that advertises FP8 loads an FP8 graph; a device that does not must refuse it at load
1846    /// rather than accept the program and fail later. Intel NPU arch 5010 takes the first branch
1847    /// and arch 40XX the second, so this is the one FP8 test that is meaningful on every device.
1848    #[test]
1849    fn fp8_advertisement_matches_what_the_device_accepts() {
1850        let Some(backend) = backend() else { return };
1851        let context = backend.create_context(ContextDesc::default()).unwrap();
1852        let artifact = crate::lower::fp8_matmul_graph(virtio_accel_tosa::DType::FP8E4M3);
1853        let outcome = backend.load_program(
1854            &context,
1855            tosa_artifact_for(&SliceSource(&artifact), crate::OPENVINO_TOSA_FP8_TARGET),
1856        );
1857        match (backend.advertises_fp8(), outcome) {
1858            (true, Ok(program)) => backend.unload_program(program).unwrap(),
1859            (true, Err(error)) => panic!(
1860                "{}: advertises FP8 but refused an FP8 graph: {error:?}",
1861                backend.device_name()
1862            ),
1863            (false, Err(_)) => {}
1864            (false, Ok(_)) => panic!(
1865                "{}: does not advertise FP8 but accepted an FP8 graph",
1866                backend.device_name()
1867            ),
1868        }
1869        backend.destroy_context(context).unwrap();
1870    }
1871
1872    /// The lowering tests assert the emitted document's shape; this asserts the real compiler
1873    /// builds a blob from it. The distinction is the whole point of the widening: a raw FP8
1874    /// MatMul reaches MLIR's verifier and is rejected, because the NPU compiler's IE dialect
1875    /// declares MatMul operands without the FP8 types.
1876    #[test]
1877    fn fp8_identity_moves_every_byte_pattern_on_the_device() {
1878        let Some(backend) = backend() else { return };
1879        // Name the device: FP8 movement works on several plugins, so a pass says nothing about
1880        // which one ran it. The evidence pin needs the device, not just the result.
1881        eprintln!(
1882            "FP8 device: {} (FP8 advertised: {})",
1883            backend.device_name(),
1884            backend.advertises_fp8()
1885        );
1886        if !backend.advertises_fp8() {
1887            return;
1888        }
1889        for case in [IDENTITY_FP8E4M3, IDENTITY_FP8E5M2] {
1890            let context = backend.create_context(ContextDesc::default()).unwrap();
1891            let program = backend
1892                .load_program(
1893                    &context,
1894                    tosa_artifact_for(&SliceSource(case.artifact), crate::OPENVINO_TOSA_FP8_TARGET),
1895                )
1896                .unwrap_or_else(|error| panic!("{}: load rejected: {error:?}", case.name));
1897            let bytes = program.slots[0].byte_len;
1898            let desc = BufferDesc::new(
1899                bytes,
1900                4096,
1901                MemoryDomain::Shared,
1902                BufferUsage::TRANSFER_SOURCE
1903                    | BufferUsage::TRANSFER_DESTINATION
1904                    | BufferUsage::PROGRAM_INPUT
1905                    | BufferUsage::PROGRAM_OUTPUT,
1906            )
1907            .unwrap();
1908            let (mut input, _) = backend
1909                .allocate_buffer(&context, desc)
1910                .unwrap()
1911                .into_parts();
1912            let (output, _) = backend
1913                .allocate_buffer(&context, desc)
1914                .unwrap()
1915                .into_parts();
1916            // Walk the encoding space: one byte per element, so NaNs, both zeros, the
1917            // subnormals and the maxima are all covered rather than sampled.
1918            let payload = (0..bytes as usize)
1919                .map(|index| (index % 256) as u8)
1920                .collect::<Vec<_>>();
1921            backend
1922                .write_buffer(&mut input, 0, &SliceSource(&payload))
1923                .unwrap();
1924            let queue = backend
1925                .create_queue(&context, QueueDesc::default())
1926                .unwrap();
1927            let bindings = [
1928                BindingRef {
1929                    slot: 0,
1930                    buffer: &input,
1931                    range: virtio_accel_core::BufferRange::new(0, bytes).unwrap(),
1932                    access: AccessMode::Read,
1933                },
1934                BindingRef {
1935                    slot: 1,
1936                    buffer: &output,
1937                    range: virtio_accel_core::BufferRange::new(0, bytes).unwrap(),
1938                    access: AccessMode::Write,
1939                },
1940            ];
1941            let event = backend
1942                .submit(&queue, &program, &bindings, Timeout::Infinite)
1943                .unwrap_or_else(|_| panic!("{}: submission failed", case.name));
1944            assert_eq!(
1945                wait_for_terminal(&backend, &event),
1946                EventState::Complete,
1947                "{}",
1948                case.name
1949            );
1950            let mut result = vec![0u8; bytes as usize];
1951            backend
1952                .read_buffer(&output, 0, &mut SliceSink(&mut result))
1953                .unwrap();
1954            assert_eq!(
1955                result, payload,
1956                "{}: FP8 movement is not bit-exact",
1957                case.name
1958            );
1959            backend.destroy_event(event).unwrap();
1960        }
1961    }
1962
1963    #[test]
1964    fn executes_device_neutral_tosa_identity_end_to_end() {
1965        let Some(backend) = backend() else { return };
1966        let context = backend.create_context(ContextDesc::default()).unwrap();
1967        let program = backend
1968            .load_program(&context, tosa_artifact(&SliceSource(IDENTITY_FP32_LOCAL)))
1969            .unwrap();
1970        let bytes = program.slots[0].byte_len;
1971        let desc = BufferDesc::new(
1972            bytes,
1973            4096,
1974            MemoryDomain::Shared,
1975            BufferUsage::TRANSFER_SOURCE
1976                | BufferUsage::TRANSFER_DESTINATION
1977                | BufferUsage::PROGRAM_INPUT
1978                | BufferUsage::PROGRAM_OUTPUT,
1979        )
1980        .unwrap();
1981        let (mut input, _) = backend
1982            .allocate_buffer(&context, desc)
1983            .unwrap()
1984            .into_parts();
1985        let (output, _) = backend
1986            .allocate_buffer(&context, desc)
1987            .unwrap()
1988            .into_parts();
1989        let payload = (1..=bytes as u32 / 4)
1990            .flat_map(|value| (value as f32).to_le_bytes())
1991            .collect::<Vec<_>>();
1992        backend
1993            .write_buffer(&mut input, 0, &SliceSource(&payload))
1994            .unwrap();
1995
1996        let queue = backend
1997            .create_queue(&context, QueueDesc::default())
1998            .unwrap();
1999        let bindings = [
2000            BindingRef {
2001                slot: 0,
2002                buffer: &input,
2003                range: virtio_accel_core::BufferRange::new(0, bytes).unwrap(),
2004                access: AccessMode::Read,
2005            },
2006            BindingRef {
2007                slot: 1,
2008                buffer: &output,
2009                range: virtio_accel_core::BufferRange::new(0, bytes).unwrap(),
2010                access: AccessMode::Write,
2011            },
2012        ];
2013        let event = backend
2014            .submit(&queue, &program, &bindings, Timeout::Infinite)
2015            .unwrap_or_else(|failure| match failure {
2016                SubmitFailure::Rejected(error) => panic!("submission rejected: {error:?}"),
2017                SubmitFailure::Indeterminate { error, .. } => {
2018                    panic!("submission indeterminate: {error:?}")
2019                }
2020            });
2021        assert_eq!(wait_for_terminal(&backend, &event), EventState::Complete);
2022        assert!(event.metadata.borrow().backings.is_empty());
2023        assert!(queue.scratch.metadata_spare.borrow().is_none());
2024
2025        let mut result = vec![0u8; bytes as usize];
2026        backend
2027            .read_buffer(&output, 0, &mut SliceSink(&mut result))
2028            .unwrap();
2029        assert_eq!(result, payload);
2030        assert_eq!(backend.direct_binding_admissions(), 2);
2031
2032        backend.destroy_event(event).unwrap();
2033        assert!(
2034            queue
2035                .scratch
2036                .metadata_spare
2037                .borrow()
2038                .as_ref()
2039                .is_some_and(|metadata| {
2040                    metadata.backings.is_empty()
2041                        && metadata.backings.capacity() >= bindings.len()
2042                        && metadata.tensors.is_empty()
2043                        && metadata.tensors.capacity() >= bindings.len()
2044                })
2045        );
2046        backend.destroy_queue(queue).unwrap();
2047        backend.unload_program(program).unwrap();
2048        backend.free_buffer(input).unwrap();
2049        backend.free_buffer(output).unwrap();
2050        backend.destroy_context(context).unwrap();
2051    }
2052
2053    #[test]
2054    fn host_transfers_are_busy_while_an_inference_holds_the_backing() {
2055        let Some(backend) = backend() else { return };
2056        let context = backend.create_context(ContextDesc::default()).unwrap();
2057        let desc = BufferDesc::new(
2058            32,
2059            4096,
2060            MemoryDomain::Shared,
2061            BufferUsage::TRANSFER_SOURCE
2062                | BufferUsage::TRANSFER_DESTINATION
2063                | BufferUsage::PROGRAM_INPUT,
2064        )
2065        .unwrap();
2066        let (mut buffer, _) = backend
2067            .allocate_buffer(&context, desc)
2068            .unwrap()
2069            .into_parts();
2070        let mut guard = EventBacking::new(Arc::clone(&buffer.allocation), AccessMode::Write);
2071        guard.acquire().unwrap();
2072        assert_eq!(
2073            backend.write_buffer(&mut buffer, 0, &SliceSource(&[0u8; 32])),
2074            Err(BackendError::Busy)
2075        );
2076        let mut sink = [0u8; 32];
2077        assert_eq!(
2078            backend.read_buffer(&buffer, 0, &mut SliceSink(&mut sink)),
2079            Err(BackendError::Busy)
2080        );
2081        drop(guard);
2082        backend
2083            .write_buffer(&mut buffer, 0, &SliceSource(&[1u8; 32]))
2084            .unwrap();
2085        backend.free_buffer(buffer).unwrap();
2086        backend.destroy_context(context).unwrap();
2087    }
2088
2089    #[test]
2090    fn misaligned_and_wrong_length_bindings_are_rejected_before_admission() {
2091        let Some(backend) = backend() else { return };
2092        let context = backend.create_context(ContextDesc::default()).unwrap();
2093        let program = backend
2094            .load_program(&context, tosa_artifact(&SliceSource(IDENTITY_FP32_LOCAL)))
2095            .unwrap();
2096        let bytes = program.slots[0].byte_len;
2097        let desc = BufferDesc::new(
2098            bytes * 2,
2099            4096,
2100            MemoryDomain::Shared,
2101            BufferUsage::TRANSFER_SOURCE
2102                | BufferUsage::TRANSFER_DESTINATION
2103                | BufferUsage::PROGRAM_INPUT
2104                | BufferUsage::PROGRAM_OUTPUT,
2105        )
2106        .unwrap();
2107        let (input, _) = backend
2108            .allocate_buffer(&context, desc)
2109            .unwrap()
2110            .into_parts();
2111        let (output, _) = backend
2112            .allocate_buffer(&context, desc)
2113            .unwrap()
2114            .into_parts();
2115        let queue = backend
2116            .create_queue(&context, QueueDesc::default())
2117            .unwrap();
2118
2119        let submit = |input_range: (u64, u64)| {
2120            let bindings = [
2121                BindingRef {
2122                    slot: 0,
2123                    buffer: &input,
2124                    range: virtio_accel_core::BufferRange::new(input_range.0, input_range.1)
2125                        .unwrap(),
2126                    access: AccessMode::Read,
2127                },
2128                BindingRef {
2129                    slot: 1,
2130                    buffer: &output,
2131                    range: virtio_accel_core::BufferRange::new(0, bytes).unwrap(),
2132                    access: AccessMode::Write,
2133                },
2134            ];
2135            match backend.submit(&queue, &program, &bindings, Timeout::Infinite) {
2136                Err(SubmitFailure::Rejected(error)) => error,
2137                Err(SubmitFailure::Indeterminate { error, .. }) => {
2138                    panic!("indeterminate: {error:?}")
2139                }
2140                Ok(_) => panic!("invalid binding was admitted"),
2141            }
2142        };
2143        // One byte into the buffer: scalar-misaligned for f32.
2144        assert_eq!(submit((1, bytes)), BackendError::Incompatible);
2145        // Wrong length for the slot's tensor.
2146        assert_eq!(submit((0, bytes * 2)), BackendError::Incompatible);
2147
2148        backend.destroy_queue(queue).unwrap();
2149        backend.unload_program(program).unwrap();
2150        backend.free_buffer(input).unwrap();
2151        backend.free_buffer(output).unwrap();
2152        backend.destroy_context(context).unwrap();
2153    }
2154}