ncnn_rust/gpu.rs
1//! Process-lifetime Vulkan initialization and explicit device selection.
2//!
3//! The native instance and cached devices remain alive until process exit. Raw
4//! users must not destroy or replace that instance, its devices, or allocators.
5use crate::{sys, Error, Result};
6use std::{ffi::CStr, marker::PhantomData, rc::Rc, sync::OnceLock};
7
8/// Storage and arithmetic policy requested from the Vulkan backend.
9///
10/// The variant is a request, not a guarantee: ncnn keeps its own capability dispatch, so a device
11/// without half-precision support stays on FP32.
12#[derive(Clone, Copy, Debug)]
13#[non_exhaustive]
14pub enum Precision {
15 /// Requests FP32 storage and arithmetic.
16 Fp32,
17 /// Requests FP16 storage and arithmetic; native capability checks can retain FP32 on
18 /// unsupported devices.
19 Fp16,
20}
21
22/// An initialized native device. Clones share the process-owned device.
23///
24/// # Thread affinity
25///
26/// The native device table is thread-affine: enumerate once per thread and keep the device, its
27/// allocator and every network that uses them on that thread. Devices coordinate process-owned
28/// runtime state, so a device is not `Send` or `Sync`.
29#[derive(Clone, Debug)]
30pub struct Device {
31 index: i32,
32 _thread: PhantomData<Rc<()>>,
33}
34
35/// Owned metadata copied from the initialized device.
36#[derive(Clone, Debug)]
37pub struct DeviceInfo {
38 /// Device index used for selection.
39 pub index: usize,
40 /// Driver-reported device name.
41 pub name: String,
42 /// Reported Vulkan API version.
43 pub api_version: u32,
44 /// PCI vendor identifier.
45 pub vendor_id: u32,
46 /// PCI device identifier.
47 pub device_id: u32,
48 /// Native device type: 0 discrete, 1 integrated, 2 virtual, 3 CPU.
49 pub device_type: u32,
50}
51
52fn initialize() -> Result<()> {
53 static STATUS: OnceLock<i32> = OnceLock::new();
54 let code = *STATUS.get_or_init(|| unsafe { sys::ncnn_rs_gpu_initialize() });
55 if code != 0 {
56 return Err(Error::Unsupported("Vulkan instance initialization failed"));
57 }
58 Ok(())
59}
60
61impl Device {
62 /// Enumerates available devices without silently substituting the CPU backend.
63 ///
64 /// The order is the native one and matches the index [`Device::new`] accepts. An empty vector
65 /// means no driver or ICD is visible, which is a missing capability rather than an empty device
66 /// list to fall back from.
67 pub fn enumerate() -> Result<Vec<DeviceInfo>> {
68 initialize()?;
69 Ok((0..unsafe { sys::ncnn_rs_gpu_count() })
70 .map(Self::metadata)
71 .collect())
72 }
73 /// Selects one device by index after validating it.
74 ///
75 /// An index the driver does not expose returns [`Error::Unsupported`].
76 /// The native device outlives this handle: every network that selects it keeps a reference.
77 pub fn new(index: usize) -> Result<Self> {
78 initialize()?;
79 let index =
80 i32::try_from(index).map_err(|_| Error::invalid("Invalid Vulkan device index"))?;
81 if unsafe { sys::ncnn_rs_gpu_valid(index) } == 0 {
82 return Err(Error::Unsupported(
83 "Vulkan device is unavailable or invalid",
84 ));
85 }
86 Ok(Self {
87 index,
88 _thread: PhantomData,
89 })
90 }
91 /// Selects the device the native runtime ranks first.
92 ///
93 /// ncnn scores the visible devices and picks one, so this is the portable choice for an
94 /// application that does not pin a GPU. Combine [`enumerate`](Self::enumerate) with
95 /// [`new`](Self::new) when a specific device matters.
96 pub fn default_device() -> Result<Self> {
97 initialize()?;
98 let index = unsafe { sys::ncnn_rs_gpu_default() };
99 if index < 0 {
100 return Err(Error::Unsupported("No Vulkan device is available"));
101 }
102 Self::new(index as usize)
103 }
104 /// Returns the copied device metadata.
105 ///
106 /// The values are read once per call, so later driver-side changes are not observed.
107 pub fn info(&self) -> DeviceInfo {
108 Self::metadata(self.index)
109 }
110 pub(crate) fn index(&self) -> i32 {
111 self.index
112 }
113 fn metadata(index: i32) -> DeviceInfo {
114 unsafe {
115 DeviceInfo {
116 index: index as usize,
117 name: CStr::from_ptr(sys::ncnn_rs_gpu_name(index))
118 .to_string_lossy()
119 .into_owned(),
120 api_version: sys::ncnn_rs_gpu_property(index, 0),
121 vendor_id: sys::ncnn_rs_gpu_property(index, 1),
122 device_id: sys::ncnn_rs_gpu_property(index, 2),
123 device_type: sys::ncnn_rs_gpu_property(index, 3),
124 }
125 }
126 }
127}
128
129use crate::{error::status, Mat, Net};
130use std::{
131 cell::Cell,
132 ffi::{c_void, CString},
133 path::Path,
134};
135
136/// A thread-affine allocator arena retained by all of its resident tensors.
137#[derive(Clone)]
138pub struct Allocator(Rc<AllocatorInner>);
139struct AllocatorInner {
140 raw: *mut c_void,
141 device: Device,
142 live_bytes: Cell<usize>,
143 peak_bytes: Cell<usize>,
144}
145impl Drop for AllocatorInner {
146 fn drop(&mut self) {
147 unsafe { sys::ncnn_rs_gpu_allocator_destroy(self.raw) }
148 }
149}
150/// A resident buffer with no unsynchronized mapped or raw access.
151pub struct Tensor {
152 raw: *mut c_void,
153 bytes: usize,
154 allocator: Allocator,
155}
156impl Drop for Tensor {
157 fn drop(&mut self) {
158 unsafe { sys::ncnn_rs_gpu_tensor_destroy(self.raw) }
159 self.allocator
160 .0
161 .live_bytes
162 .set(self.allocator.0.live_bytes.get() - self.bytes);
163 }
164}
165impl Device {
166 /// Creates a thread-affine allocator on this device.
167 pub fn allocator(&self) -> Result<Allocator> {
168 let raw = unsafe { sys::ncnn_rs_gpu_allocator_create(self.index) };
169 if raw.is_null() {
170 return Err(Error::Native(-1));
171 }
172 Ok(Allocator(Rc::new(AllocatorInner {
173 raw,
174 device: self.clone(),
175 live_bytes: Cell::new(0),
176 peak_bytes: Cell::new(0),
177 })))
178 }
179 /// Reports the native device-wide heap budget in MiB, not application usage.
180 pub fn heap_budget_mib(&self) -> usize {
181 unsafe { sys::ncnn_rs_gpu_heap_budget(self.index) }
182 }
183 /// Returns the borrowed native VkDevice handle. This does not transfer ownership.
184 pub fn raw_device_handle(&self) -> u64 {
185 unsafe { sys::ncnn_rs_gpu_device_handle(self.index) }
186 }
187 /// Serializes native compatibility metadata, shaders, and Vulkan pipeline data.
188 pub fn save_pipeline_cache(&self, path: impl AsRef<Path>) -> Result<()> {
189 std::fs::write(path, self.pipeline_cache()?)?;
190 Ok(())
191 }
192 /// Returns the serialized pipeline cache for storage outside the file system.
193 ///
194 /// The bytes are what [`save_pipeline_cache`](Self::save_pipeline_cache) writes, so a caller can
195 /// keep them in memory, in an archive or in another process's transport.
196 pub fn pipeline_cache(&self) -> Result<Vec<u8>> {
197 let mut data = std::ptr::null_mut();
198 let mut size = 0;
199 status(unsafe { sys::ncnn_rs_gpu_cache_save(self.index, &mut data, &mut size) })?;
200 let bytes = unsafe { std::slice::from_raw_parts(data, size) }.to_vec();
201 unsafe { sys::ncnn_rs_gpu_cache_free(data) };
202 Ok(bytes)
203 }
204 /// Rejects incompatible or corrupted native cache headers and payload hashes.
205 pub fn load_pipeline_cache(&self, path: impl AsRef<Path>) -> Result<()> {
206 self.set_pipeline_cache(&std::fs::read(path)?)
207 }
208 /// Loads a serialized pipeline cache produced by [`pipeline_cache`](Self::pipeline_cache).
209 pub fn set_pipeline_cache(&self, data: &[u8]) -> Result<()> {
210 status(unsafe { sys::ncnn_rs_gpu_cache_load(self.index, data.as_ptr(), data.len()) })
211 }
212}
213impl Allocator {
214 /// Reports live tensor storage and its high-water mark, excluding allocator pools, staging, workspace, and driver allocations.
215 /// Imported storage is included without implying ownership.
216 pub fn tensor_bytes(&self) -> (usize, usize) {
217 (self.0.live_bytes.get(), self.0.peak_bytes.get())
218 }
219 /// Uploads and waits before returning resident FP32 storage.
220 ///
221 /// A device that refuses the storage reports the refusal as a native failure during
222 /// `Vulkan upload`; the allocator, the tensors it already returned and later requests stay
223 /// usable.
224 pub fn upload(&self, mat: &Mat) -> Result<Tensor> {
225 let info = mat.info();
226 if info.elemsize != 4 || info.elempack != 1 || info.dims == 0 {
227 return Err(Error::invalid(
228 "Upload requires nonempty unpacked FP32 storage",
229 ));
230 }
231 let raw = unsafe { sys::ncnn_rs_gpu_upload(self.0.raw, mat.as_raw()) };
232 self.tensor(raw, "Vulkan upload")
233 }
234 fn tensor(&self, raw: *mut c_void, operation: &'static str) -> Result<Tensor> {
235 if raw.is_null() {
236 return Err(Error::NativeAt(operation, -1));
237 }
238 let bytes = unsafe { sys::ncnn_rs_gpu_tensor_bytes(raw) };
239 let Some(live) = self.0.live_bytes.get().checked_add(bytes) else {
240 unsafe { sys::ncnn_rs_gpu_tensor_destroy(raw) };
241 return Err(Error::invalid("Tensor byte counter overflow"));
242 };
243 self.0.live_bytes.set(live);
244 self.0.peak_bytes.set(self.0.peak_bytes.get().max(live));
245 Ok(Tensor {
246 raw,
247 bytes,
248 allocator: self.clone(),
249 })
250 }
251 /// Records resident inference. Submission occurs only in `Command::wait`.
252 pub fn command<'a>(&self, net: &'a Net) -> Result<Command<'a>> {
253 if net.vulkan_device().map(Device::index) != Some(self.0.device.index) {
254 return Err(Error::invalid("Network and allocator devices differ"));
255 }
256 let raw = unsafe { sys::ncnn_rs_gpu_command_create(self.0.raw, net.as_raw()) };
257 if raw.is_null() {
258 return Err(Error::NativeAt("Vulkan command creation", -1));
259 }
260 Ok(Command {
261 raw,
262 allocator: self.clone(),
263 _net: net,
264 inputs: Vec::new(),
265 outputs: Vec::new(),
266 recorded: false,
267 failed: false,
268 })
269 }
270 /// Borrows a caller-owned same-device Vulkan storage buffer as unpacked FP32.
271 ///
272 /// # Safety
273 /// The buffer must belong to `Device::raw_device_handle`, support storage and
274 /// transfer usage, and remain allocated and exclusively available until every
275 /// tensor and command using it is dropped. Offset must satisfy native Vulkan
276 /// storage-buffer alignment. Access/stage masks must describe its last use.
277 /// External queues must be synchronized before and after Rust use. Neither
278 /// the buffer nor its memory is freed by this API. Device adoption is absent.
279 pub unsafe fn import_buffer(
280 &self,
281 buffer: u64,
282 offset: usize,
283 capacity: usize,
284 elements: usize,
285 access: u32,
286 stage: u32,
287 ) -> Result<Tensor> {
288 if buffer == 0
289 || elements == 0
290 || elements > i32::MAX as usize
291 || elements.checked_mul(4).is_none_or(|n| n > capacity)
292 {
293 return Err(Error::invalid("Invalid external buffer range"));
294 }
295 self.tensor(
296 unsafe {
297 sys::ncnn_rs_gpu_import(
298 self.0.raw,
299 buffer,
300 offset,
301 capacity,
302 elements as i32,
303 access,
304 stage,
305 )
306 },
307 "Vulkan import",
308 )
309 }
310}
311impl Tensor {
312 /// Borrows completed resident storage without mapping it.
313 pub fn guard(&self) -> TensorGuard<'_> {
314 TensorGuard { tensor: self }
315 }
316 /// Returns logical native storage bytes including native tensor padding.
317 ///
318 /// This is the amount the allocator accounts for, so it can exceed the element count times the
319 /// element width. [`Allocator::tensor_bytes`] sums the same figure.
320 pub fn storage_bytes(&self) -> usize {
321 unsafe { sys::ncnn_rs_gpu_tensor_bytes(self.raw) }
322 }
323 /// Downloads and synchronizes into detached CPU-owned FP32 storage.
324 ///
325 /// The call blocks and copies, which is the cost the performance page records as the
326 /// upload-download round trip. Read residency with [`TensorGuard::buffer_descriptor`] when the
327 /// values must stay on the device; a refusal is reported as
328 /// [`Error::NativeAt`] naming the operation.
329 pub fn download(&self) -> Result<Mat> {
330 let mut raw = std::ptr::null_mut();
331 status(unsafe { sys::ncnn_rs_gpu_download(self.allocator.0.raw, self.raw, &mut raw) })?;
332 unsafe { Mat::from_raw_owned(raw, true) }
333 }
334}
335/// A recording owner. Outputs remain inaccessible until blocking completion.
336/// Dropping or forgetting this owner cannot expose unfinished output storage.
337/// The pinned native API does not provide nonblocking submit or fence polling.
338///
339/// Recording retains a network borrow until completion or cancellation.
340///
341/// ```compile_fail
342/// use ncnn_rust::{gpu::Allocator, Net};
343/// fn cannot_clear(allocator: &Allocator, net: &mut Net) {
344/// let command = allocator.command(net).unwrap();
345/// net.clear();
346/// command.wait().unwrap();
347/// }
348/// ```
349pub struct Command<'a> {
350 raw: *mut c_void,
351 allocator: Allocator,
352 _net: &'a Net,
353 inputs: Vec<&'a Tensor>,
354 outputs: Vec<Tensor>,
355 recorded: bool,
356 failed: bool,
357}
358impl<'a> Command<'a> {
359 /// Records one resident input for this command.
360 ///
361 /// The tensor must belong to the same device as the allocator, and inputs have to be recorded
362 /// before the first [`extract`](Self::extract). A rejected recording leaves the command in a
363 /// failed state that only dropping it resolves.
364 pub fn input(&mut self, name: &str, tensor: &'a Tensor) -> Result<()> {
365 if self.failed {
366 return Err(Error::invalid("Recording failed and must be cancelled"));
367 }
368 if tensor.allocator.0.device.index != self.allocator.0.device.index {
369 return Err(Error::invalid("Tensor device differs"));
370 }
371 if self.recorded {
372 return Err(Error::invalid(
373 "Inputs cannot change after recording outputs",
374 ));
375 }
376 let name = CString::new(name)?;
377 self.inputs.push(tensor);
378 let result =
379 status(unsafe { sys::ncnn_rs_gpu_command_input(self.raw, name.as_ptr(), tensor.raw) });
380 self.failed = result.is_err();
381 result
382 }
383 /// Records an output and returns its index in the completed output vector.
384 ///
385 /// The output storage belongs to the allocator from this call on, so it counts towards
386 /// [`Allocator::tensor_bytes`] before any work is submitted. Recording an output closes input
387 /// recording for this command.
388 pub fn extract(&mut self, name: &str) -> Result<usize> {
389 if self.failed {
390 return Err(Error::invalid("Recording failed and must be cancelled"));
391 }
392 let name = CString::new(name)?;
393 self.recorded = true;
394 let raw = unsafe { sys::ncnn_rs_gpu_command_extract(self.raw, name.as_ptr()) };
395 match self.allocator.tensor(raw, "Vulkan command output") {
396 Ok(tensor) => self.outputs.push(tensor),
397 Err(error) => {
398 self.failed = true;
399 return Err(error);
400 }
401 }
402 Ok(self.outputs.len() - 1)
403 }
404 /// Submits recorded work and blocks for native fence completion.
405 ///
406 /// The returned tensors are completed and safe to read through
407 /// [`Tensor::download`] or [`Tensor::guard`]. A native recording failure cancels the command
408 /// instead of submitting it, so a failed record never reaches the device.
409 pub fn wait(mut self) -> Result<Vec<Tensor>> {
410 if self.failed {
411 return Err(Error::invalid("Recording failed and must be cancelled"));
412 }
413 status(unsafe { sys::ncnn_rs_gpu_command_wait(self.raw) })?;
414 Ok(std::mem::take(&mut self.outputs))
415 }
416}
417impl Drop for Command<'_> {
418 fn drop(&mut self) {
419 unsafe { sys::ncnn_rs_gpu_command_destroy(self.raw) }
420 }
421}
422
423/// A borrowed view of completed resident storage. Forgetting this guard does not
424/// release its tensor or grant access to pending commands. The shared borrow
425/// prevents safe destruction while the guard remains usable.
426pub struct TensorGuard<'a> {
427 tensor: &'a Tensor,
428}
429
430/// A nonowning Vulkan buffer descriptor. Values remain valid only while the
431/// tensor guard and its device remain alive.
432#[derive(Debug, Clone, Copy)]
433pub struct BufferDescriptor {
434 /// Native `VkBuffer` handle.
435 pub buffer: u64,
436 /// Byte offset of the tensor inside the buffer.
437 pub offset: usize,
438 /// Buffer capacity in bytes.
439 pub capacity: usize,
440 /// Native access flags recorded for the descriptor.
441 pub access: u32,
442 /// Native pipeline-stage flags recorded for the descriptor.
443 pub stage: u32,
444}
445impl TensorGuard<'_> {
446 /// Synchronizes and returns an independent CPU tensor.
447 pub fn download(&self) -> Result<Mat> {
448 self.tensor.download()
449 }
450 /// Exposes a descriptor for explicitly synchronized external interoperability.
451 ///
452 /// # Safety
453 /// External use must not mutate storage while any Rust command or tensor
454 /// uses it. The caller synchronizes queues and restores the recorded access
455 /// state before subsequent Rust use, and never destroys this borrowed buffer.
456 pub unsafe fn buffer_descriptor(&self) -> Result<BufferDescriptor> {
457 let mut d = BufferDescriptor {
458 buffer: 0,
459 offset: 0,
460 capacity: 0,
461 access: 0,
462 stage: 0,
463 };
464 status(unsafe {
465 sys::ncnn_rs_gpu_buffer_info(
466 self.tensor.raw,
467 &mut d.buffer,
468 &mut d.offset,
469 &mut d.capacity,
470 &mut d.access,
471 &mut d.stage,
472 )
473 })?;
474 Ok(d)
475 }
476}