|
| 1 | +use std::{ffi::CStr, os::raw::c_int}; |
| 2 | +use whisper_rs_sys::{ |
| 3 | + ggml_backend_buffer_type_t, ggml_backend_vk_buffer_type, ggml_backend_vk_get_device_count, |
| 4 | + ggml_backend_vk_get_device_description, ggml_backend_vk_get_device_memory, |
| 5 | +}; |
| 6 | + |
| 7 | +#[derive(Debug, Clone)] |
| 8 | +pub struct VKVram { |
| 9 | + pub free: usize, |
| 10 | + pub total: usize, |
| 11 | +} |
| 12 | + |
| 13 | +/// Human-readable device information |
| 14 | +#[derive(Debug, Clone)] |
| 15 | +pub struct VkDeviceInfo { |
| 16 | + pub id: i32, |
| 17 | + pub name: String, |
| 18 | + pub vram: VKVram, |
| 19 | + /// Buffer type to pass to `whisper::Backend::create_buffer` |
| 20 | + pub buf_type: ggml_backend_buffer_type_t, |
| 21 | +} |
| 22 | +/// Enumerate every physical GPU ggml can see. |
| 23 | +/// |
| 24 | +/// Note: integrated GPUs are returned *after* discrete ones, |
| 25 | +/// mirroring ggml’s C logic. |
| 26 | +pub fn list_devices() -> Vec<VkDeviceInfo> { |
| 27 | + unsafe { |
| 28 | + let n = ggml_backend_vk_get_device_count(); |
| 29 | + (0..n) |
| 30 | + .map(|id| { |
| 31 | + // 256 bytes is plenty (spec says 128 is enough) |
| 32 | + let mut tmp = [0i8; 256]; |
| 33 | + ggml_backend_vk_get_device_description(id as c_int, tmp.as_mut_ptr(), tmp.len()); |
| 34 | + let mut free = 0usize; |
| 35 | + let mut total = 0usize; |
| 36 | + ggml_backend_vk_get_device_memory(id, &mut free, &mut total); |
| 37 | + VkDeviceInfo { |
| 38 | + id, |
| 39 | + name: CStr::from_ptr(tmp.as_ptr()).to_string_lossy().into_owned(), |
| 40 | + vram: VKVram { free, total }, |
| 41 | + buf_type: ggml_backend_vk_buffer_type(id as usize), |
| 42 | + } |
| 43 | + }) |
| 44 | + .collect() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod vulkan_tests { |
| 50 | + use super::*; |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn enumerate_must_not_panic() { |
| 54 | + let _ = list_devices(); |
| 55 | + } |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn sane_device_info() { |
| 59 | + let gpus = list_devices(); |
| 60 | + let mut seen = std::collections::HashSet::new(); |
| 61 | + |
| 62 | + for dev in &gpus { |
| 63 | + assert!(seen.insert(dev.id), "duplicated id {}", dev.id); |
| 64 | + assert!(!dev.name.trim().is_empty(), "GPU {} has empty name", dev.id); |
| 65 | + assert!( |
| 66 | + dev.vram.total >= dev.vram.free, |
| 67 | + "GPU {} total < free", |
| 68 | + dev.id |
| 69 | + ); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments