Skip to main content

transcribe_cpp/
backend.rs

1//! Backend module loading and compute-device discovery.
2//!
3//! In a static (or plain `shared`) build the compiled-in backends are already
4//! registered and [`init_backends`] is a harmless no-op. In a `dynamic-backends`
5//! build the compute backends are loadable modules; a host points the library at
6//! the provider directory ONCE, before the first model load — use
7//! [`init_backends_default`] when the modules sit next to libtranscribe, or
8//! [`init_backends`] with an explicit bundled provider directory. See the C
9//! header's backend-module section for the degradation contract.
10
11use std::ffi::CString;
12use std::path::Path;
13
14use transcribe_cpp_sys as sys;
15use transcribe_cpp_types::{Backend, BackendMask, DeviceType};
16
17use crate::error::{check, Result};
18use crate::result::{owned_opt_str, owned_str};
19use crate::types::{FromRaw, ToRaw};
20
21impl FromRaw<sys::transcribe_device_type> for DeviceType {
22    fn from_raw(raw: sys::transcribe_device_type) -> Self {
23        use sys::transcribe_device_type as T;
24        match raw {
25            T::TRANSCRIBE_DEVICE_TYPE_CPU => DeviceType::Cpu,
26            T::TRANSCRIBE_DEVICE_TYPE_GPU => DeviceType::Gpu,
27            T::TRANSCRIBE_DEVICE_TYPE_IGPU => DeviceType::Igpu,
28            T::TRANSCRIBE_DEVICE_TYPE_ACCEL => DeviceType::Accel,
29            _ => DeviceType::Unknown,
30        }
31    }
32}
33
34/// One registered compute device.
35#[derive(Debug, Clone)]
36pub struct Device {
37    /// ggml device name, e.g. "Metal".
38    pub name: String,
39    /// Human-readable description, e.g. "Apple M4 Max".
40    pub description: String,
41    /// Classified vendor kind: "cpu", "accel", "metal", "vulkan", "cuda",
42    /// "rocm", "sycl", "gpu", or "unknown".
43    pub kind: String,
44    /// The CPU/GPU/IGPU/ACCEL axis, orthogonal to [`Device::kind`].
45    pub device_type: DeviceType,
46    /// Stable hardware id when the backend reports one (PCI bus id for PCI
47    /// devices), or `None` (e.g. Metal).
48    pub device_id: Option<String>,
49    /// Device UUID (lower-case 8-4-4-4-12 hex), or `None` (Vulkan and CUDA
50    /// report one). Not guaranteed unique.
51    pub device_uuid: Option<String>,
52    /// Reported device memory capacity in bytes, or 0 if unreported.
53    pub memory_total: u64,
54    /// Available device memory in bytes — a snapshot at the time this was
55    /// queried, or 0 if unreported. Re-query (via [`devices`] or
56    /// [`crate::Model::device`]) to refresh it; the value is backend-defined
57    /// and not comparable across device kinds.
58    pub memory_free: u64,
59    /// Registry index when this device came from [`devices`]. This is useful
60    /// for display only; pass the [`Device`] itself to [`ModelOptions`](crate::ModelOptions) for
61    /// exact selection. Registry indices are not stable across processes.
62    pub index: Option<usize>,
63    pub(crate) handle: sys::transcribe_device_t,
64}
65
66// Device handles are immutable process-lifetime registry entries. Backend
67// registration must finish before enumeration, so sharing a handle is safe.
68unsafe impl Send for Device {}
69unsafe impl Sync for Device {}
70
71impl PartialEq for Device {
72    fn eq(&self, other: &Self) -> bool {
73        self.handle == other.handle
74    }
75}
76
77impl Eq for Device {}
78
79impl Device {
80    /// Build a [`Device`] from the raw FFI struct filled by the library.
81    /// `index` is the registry index when the device came from enumeration,
82    /// or `None` when it came from a loaded model.
83    pub(crate) fn from_raw(
84        raw: &sys::transcribe_device_info,
85        handle: sys::transcribe_device_t,
86        index: Option<usize>,
87    ) -> Device {
88        Device {
89            name: owned_str(raw.name),
90            description: owned_str(raw.description),
91            kind: owned_str(raw.kind),
92            device_type: DeviceType::from_raw(raw.device_type),
93            device_id: owned_opt_str(raw.device_id),
94            device_uuid: owned_opt_str(raw.device_uuid),
95            memory_total: raw.memory_total,
96            memory_free: raw.memory_free,
97            index,
98            handle,
99        }
100    }
101}
102
103/// Load backend modules from `dir` (dynamic builds) and register their
104/// devices. A no-op in static builds. Call once, before the first model load.
105///
106/// Errors with [`crate::Error::Backend`] if, after loading, the process has no
107/// registered compute device (a dynamic build pointed at a directory with no
108/// usable modules). This call is idempotent per directory and NOT retryable in
109/// the same process.
110///
111/// This mutates the native process-global device registry. Complete every
112/// backend-init call before other threads enumerate devices, query backend
113/// availability, or load models; the native registry does not support racing
114/// registration against those operations.
115pub fn init_backends(dir: impl AsRef<Path>) -> Result<()> {
116    let dir = dir.as_ref();
117    // Pass the path bytes through faithfully (Unix) / reject non-UTF-8 (Windows),
118    // matching model loading — never lossily mangle a path with to_string_lossy.
119    let c_dir = CString::new(crate::model::path_bytes(dir)?)?;
120    let status = unsafe { sys::transcribe_init_backends(c_dir.as_ptr()) };
121    check(status, "init_backends")
122}
123
124/// Load the backend modules the way the build expects, with no caller-supplied
125/// path.
126///
127/// - **Compiled-in builds** (the default static build, or a plain `shared`
128///   build): a no-op returning `Ok(())` — the backends are already registered.
129/// - **`dynamic-backends` builds**: resolves the directory containing the
130///   loaded libtranscribe and scans only that directory. Ship the backend
131///   modules next to libtranscribe for this helper to find them.
132///
133/// If your app uses a different layout, call [`init_backends`] with that
134/// resolved module directory instead. Like [`init_backends`], this is
135/// idempotent and must run once before the first model load. It must also
136/// complete before other threads enumerate devices or query backend
137/// availability; see [`init_backends`] for the registry-ordering contract.
138pub fn init_backends_default() -> Result<()> {
139    let status = unsafe { sys::transcribe_init_backends_default() };
140    check(status, "init_backends_default")
141}
142
143/// [`init_backends`] / [`init_backends_default`] (`dir` = `None`) with an
144/// allowed-backend mask. The mask is fixed at first backend registration;
145/// call this first, once per process. A later call with a different
146/// effective mask returns [`crate::Error::Backend`].
147///
148/// ```no_run
149/// use transcribe_cpp::{init_backends_with, Backend, BackendMask};
150/// // A CPU fallback worker: never let the GPU driver load.
151/// init_backends_with(None::<&std::path::Path>, BackendMask::for_backend(Backend::Cpu))?;
152/// # Ok::<(), transcribe_cpp::Error>(())
153/// ```
154pub fn init_backends_with(dir: Option<impl AsRef<Path>>, allowed: BackendMask) -> Result<()> {
155    let c_dir = match dir {
156        Some(dir) => Some(CString::new(crate::model::path_bytes(dir.as_ref())?)?),
157        None => None,
158    };
159    let mut params: sys::transcribe_backend_init_params = unsafe { std::mem::zeroed() };
160    unsafe { sys::transcribe_backend_init_params_init(&mut params) };
161    params.artifact_dir = c_dir.as_ref().map_or(std::ptr::null(), |d| d.as_ptr());
162    params.allowed_backends = allowed.bits();
163    let status = unsafe { sys::transcribe_init_backends_ex(&params) };
164    check(status, "init_backends_with")
165}
166
167/// The effective mask: [`init_backends_with`]'s (ALL until then) narrowed
168/// by `TRANSCRIBE_BACKENDS`.
169pub fn allowed_backends() -> BackendMask {
170    BackendMask::from_bits(unsafe { sys::transcribe_allowed_backends() })
171}
172
173/// The number of compute devices currently registered.
174///
175/// Do not race this query with [`init_backends`] or [`init_backends_default`].
176pub fn device_count() -> usize {
177    let n = unsafe { sys::transcribe_device_count() };
178    n.max(0) as usize
179}
180
181/// Every registered compute device.
182///
183/// Do not race enumeration with [`init_backends`] or
184/// [`init_backends_default`]. Finish backend registration before sharing
185/// devices across threads.
186pub fn devices() -> Vec<Device> {
187    let mut out = Vec::with_capacity(device_count());
188    for i in 0..device_count() as i32 {
189        let handle = unsafe { sys::transcribe_device_get(i) };
190        if handle.is_null() {
191            continue;
192        }
193        let mut raw: sys::transcribe_device_info = unsafe { std::mem::zeroed() };
194        unsafe { sys::transcribe_device_info_init(&mut raw) };
195        let status = unsafe { sys::transcribe_device_get_info(handle, &mut raw) };
196        if status == sys::transcribe_status::TRANSCRIBE_OK {
197            out.push(Device::from_raw(&raw, handle, Some(i as usize)));
198        }
199    }
200    out
201}
202
203/// Whether a backend request can be satisfied by some registered device. This
204/// is the probe to turn `Backend::Vulkan` on a machine without Vulkan into a
205/// clear error instead of a failed model load. Do not race this query with
206/// [`init_backends`] or [`init_backends_default`].
207pub fn backend_available(backend: Backend) -> bool {
208    unsafe { sys::transcribe_backend_available(backend.to_raw()) }
209}