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 /// Reported device memory capacity in bytes, or 0 if unreported.
50 pub memory_total: u64,
51 /// Available device memory in bytes — a snapshot at the time this was
52 /// queried, or 0 if unreported. Re-query (via [`devices`] or
53 /// [`crate::Model::device`]) to refresh it; the value is backend-defined
54 /// and not comparable across device kinds.
55 pub memory_free: u64,
56 /// Registry index when this device came from [`devices`]. This is useful
57 /// for display only; pass the [`Device`] itself to [`ModelOptions`](crate::ModelOptions) for
58 /// exact selection. Registry indices are not stable across processes.
59 pub index: Option<usize>,
60 pub(crate) handle: sys::transcribe_device_t,
61}
62
63// Device handles are immutable process-lifetime registry entries. Backend
64// registration must finish before enumeration, so sharing a handle is safe.
65unsafe impl Send for Device {}
66unsafe impl Sync for Device {}
67
68impl PartialEq for Device {
69 fn eq(&self, other: &Self) -> bool {
70 self.handle == other.handle
71 }
72}
73
74impl Eq for Device {}
75
76impl Device {
77 /// Build a [`Device`] from the raw FFI struct filled by the library.
78 /// `index` is the registry index when the device came from enumeration,
79 /// or `None` when it came from a loaded model.
80 pub(crate) fn from_raw(
81 raw: &sys::transcribe_device_info,
82 handle: sys::transcribe_device_t,
83 index: Option<usize>,
84 ) -> Device {
85 Device {
86 name: owned_str(raw.name),
87 description: owned_str(raw.description),
88 kind: owned_str(raw.kind),
89 device_type: DeviceType::from_raw(raw.device_type),
90 device_id: owned_opt_str(raw.device_id),
91 memory_total: raw.memory_total,
92 memory_free: raw.memory_free,
93 index,
94 handle,
95 }
96 }
97}
98
99/// Load backend modules from `dir` (dynamic builds) and register their
100/// devices. A no-op in static builds. Call once, before the first model load.
101///
102/// Errors with [`crate::Error::Backend`] if, after loading, the process has no
103/// registered compute device (a dynamic build pointed at a directory with no
104/// usable modules). This call is idempotent per directory and NOT retryable in
105/// the same process.
106///
107/// This mutates the native process-global device registry. Complete every
108/// backend-init call before other threads enumerate devices, query backend
109/// availability, or load models; the native registry does not support racing
110/// registration against those operations.
111pub fn init_backends(dir: impl AsRef<Path>) -> Result<()> {
112 let dir = dir.as_ref();
113 // Pass the path bytes through faithfully (Unix) / reject non-UTF-8 (Windows),
114 // matching model loading — never lossily mangle a path with to_string_lossy.
115 let c_dir = CString::new(crate::model::path_bytes(dir)?)?;
116 let status = unsafe { sys::transcribe_init_backends(c_dir.as_ptr()) };
117 check(status, "init_backends")
118}
119
120/// Load the backend modules the way the build expects, with no caller-supplied
121/// path.
122///
123/// - **Compiled-in builds** (the default static build, or a plain `shared`
124/// build): a no-op returning `Ok(())` — the backends are already registered.
125/// - **`dynamic-backends` builds**: resolves the directory containing the
126/// loaded libtranscribe and scans only that directory. Ship the backend
127/// modules next to libtranscribe for this helper to find them.
128///
129/// If your app uses a different layout, call [`init_backends`] with that
130/// resolved module directory instead. Like [`init_backends`], this is
131/// idempotent and must run once before the first model load. It must also
132/// complete before other threads enumerate devices or query backend
133/// availability; see [`init_backends`] for the registry-ordering contract.
134pub fn init_backends_default() -> Result<()> {
135 let status = unsafe { sys::transcribe_init_backends_default() };
136 check(status, "init_backends_default")
137}
138
139/// [`init_backends`] / [`init_backends_default`] (`dir` = `None`) with an
140/// allowed-backend mask. The mask is fixed at first backend registration;
141/// call this first, once per process. A later call with a different
142/// effective mask returns [`crate::Error::Backend`].
143///
144/// ```no_run
145/// use transcribe_cpp::{init_backends_with, Backend, BackendMask};
146/// // A CPU fallback worker: never let the GPU driver load.
147/// init_backends_with(None::<&std::path::Path>, BackendMask::for_backend(Backend::Cpu))?;
148/// # Ok::<(), transcribe_cpp::Error>(())
149/// ```
150pub fn init_backends_with(dir: Option<impl AsRef<Path>>, allowed: BackendMask) -> Result<()> {
151 let c_dir = match dir {
152 Some(dir) => Some(CString::new(crate::model::path_bytes(dir.as_ref())?)?),
153 None => None,
154 };
155 let mut params: sys::transcribe_backend_init_params = unsafe { std::mem::zeroed() };
156 unsafe { sys::transcribe_backend_init_params_init(&mut params) };
157 params.artifact_dir = c_dir.as_ref().map_or(std::ptr::null(), |d| d.as_ptr());
158 params.allowed_backends = allowed.bits();
159 let status = unsafe { sys::transcribe_init_backends_ex(¶ms) };
160 check(status, "init_backends_with")
161}
162
163/// The effective mask: [`init_backends_with`]'s (ALL until then) narrowed
164/// by `TRANSCRIBE_BACKENDS`.
165pub fn allowed_backends() -> BackendMask {
166 BackendMask::from_bits(unsafe { sys::transcribe_allowed_backends() })
167}
168
169/// The number of compute devices currently registered.
170///
171/// Do not race this query with [`init_backends`] or [`init_backends_default`].
172pub fn device_count() -> usize {
173 let n = unsafe { sys::transcribe_device_count() };
174 n.max(0) as usize
175}
176
177/// Every registered compute device.
178///
179/// Do not race enumeration with [`init_backends`] or
180/// [`init_backends_default`]. Finish backend registration before sharing
181/// devices across threads.
182pub fn devices() -> Vec<Device> {
183 let mut out = Vec::with_capacity(device_count());
184 for i in 0..device_count() as i32 {
185 let handle = unsafe { sys::transcribe_device_get(i) };
186 if handle.is_null() {
187 continue;
188 }
189 let mut raw: sys::transcribe_device_info = unsafe { std::mem::zeroed() };
190 unsafe { sys::transcribe_device_info_init(&mut raw) };
191 let status = unsafe { sys::transcribe_device_get_info(handle, &mut raw) };
192 if status == sys::transcribe_status::TRANSCRIBE_OK {
193 out.push(Device::from_raw(&raw, handle, Some(i as usize)));
194 }
195 }
196 out
197}
198
199/// Whether a backend request can be satisfied by some registered device. This
200/// is the probe to turn `Backend::Vulkan` on a machine without Vulkan into a
201/// clear error instead of a failed model load. Do not race this query with
202/// [`init_backends`] or [`init_backends_default`].
203pub fn backend_available(backend: Backend) -> bool {
204 unsafe { sys::transcribe_backend_available(backend.to_raw()) }
205}