Skip to main content

transcribe_cpp/
model.rs

1//! [`Model`] — a loaded GGUF, shareable across threads.
2//!
3//! A `Model` is `Arc`-backed and `Send + Sync`: cloning it is cheap and hands
4//! out another handle to the same native model. The native model is freed when
5//! the last handle AND every [`Session`](crate::Session) derived from it have
6//! been dropped — Rust ownership gives the C "model must outlive its sessions"
7//! contract (and close-ordering safety) for free, in any drop order.
8//!
9//! The `Arc` also carries the per-model compute lock that enforces the C
10//! library's 0.x concurrency limitation: at most one `run` / `run_batch` /
11//! active stream may be in flight across ALL sessions of a model. One-shot
12//! runs/batches queue on the lock (serialized); an *active stream* spans many
13//! native calls (`begin`→`feed`*→`finalize`), so the lock also carries a flag
14//! marking a stream in flight — any run/batch/stream that would overlap it is
15//! refused with [`Error::Busy`](crate::Error) rather than allowed to race.
16
17use std::ffi::CString;
18use std::path::Path;
19use std::sync::{Arc, Mutex};
20
21use transcribe_cpp_sys as sys;
22
23use crate::error::{check, Result};
24use crate::result::owned_str;
25use crate::session::Session;
26use crate::types::{Backend, ExtSlot, Feature, TimestampKind};
27use crate::version;
28
29/// Options for loading a model.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ModelOptions {
32    /// Which backend to request. Default [`Backend::Auto`].
33    pub backend: Backend,
34    /// Reserved for multi-device selection; must be 0 in 0.x.
35    pub gpu_device: i32,
36}
37
38impl Default for ModelOptions {
39    fn default() -> Self {
40        ModelOptions {
41            backend: Backend::Auto,
42            gpu_device: 0,
43        }
44    }
45}
46
47/// Immutable, model-level capabilities read from GGUF metadata.
48#[derive(Debug, Clone, PartialEq)]
49pub struct Capabilities {
50    pub native_sample_rate: i32,
51    /// Supported language codes (empty if the model is language-agnostic).
52    pub languages: Vec<String>,
53    /// The finest timestamp granularity the model can produce.
54    pub max_timestamp_kind: TimestampKind,
55    pub supports_language_detect: bool,
56    pub supports_translate: bool,
57    pub supports_streaming: bool,
58    pub supports_spec_decode: bool,
59    /// Longest accepted audio in ms (0 = no practical limit).
60    pub max_audio_ms: i64,
61}
62
63/// The native model handle plus the per-model compute lock, shared via `Arc`.
64pub(crate) struct ModelInner {
65    pub(crate) ptr: *mut sys::transcribe_model,
66    /// Serializes the compute path across all sessions of this model. The bool
67    /// is `true` while a stream is ACTIVE (from `begin` until the earliest of
68    /// `finalize` / `reset` / the `Stream` being dropped); a held lock plus a
69    /// `true` flag is how `run`/`run_batch`/`stream` detect and refuse an
70    /// overlapping compute. See the module docs.
71    pub(crate) compute_lock: Mutex<bool>,
72}
73
74// SAFETY: the native model is documented thread-safe for query + session
75// creation; the compute path is serialized by `compute_lock`. The raw pointer
76// is only ever used behind `&ModelInner`, never mutated through aliasing.
77unsafe impl Send for ModelInner {}
78unsafe impl Sync for ModelInner {}
79
80impl Drop for ModelInner {
81    fn drop(&mut self) {
82        // Only reached once every Session (each holding an Arc clone) is gone.
83        unsafe { sys::transcribe_model_free(self.ptr) };
84    }
85}
86
87/// A loaded transcription model.
88#[derive(Clone)]
89pub struct Model {
90    pub(crate) inner: Arc<ModelInner>,
91}
92
93impl std::fmt::Debug for Model {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("Model")
96            .field("arch", &self.arch())
97            .field("variant", &self.variant())
98            .field("backend", &self.backend())
99            .finish()
100    }
101}
102
103impl Model {
104    /// Load a GGUF model from disk with default options.
105    pub fn load(path: impl AsRef<Path>) -> Result<Model> {
106        Model::load_with(path, &ModelOptions::default())
107    }
108
109    /// Load a GGUF model from disk with explicit options.
110    pub fn load_with(path: impl AsRef<Path>, options: &ModelOptions) -> Result<Model> {
111        // Pre-1.0 base-version lock against the loaded library (once).
112        version::ensure_compatible()?;
113
114        let path = path.as_ref();
115        let c_path = CString::new(path_bytes(path)?)?;
116
117        let mut params: sys::transcribe_model_load_params = unsafe { std::mem::zeroed() };
118        unsafe { sys::transcribe_model_load_params_init(&mut params) };
119        params.backend = options.backend.to_raw();
120        params.gpu_device = options.gpu_device;
121
122        let mut out: *mut sys::transcribe_model = std::ptr::null_mut();
123        let status = unsafe { sys::transcribe_model_load_file(c_path.as_ptr(), &params, &mut out) };
124        check_model_load(status, &format!("load {}", path.display()))?;
125        debug_assert!(!out.is_null());
126
127        Ok(Model {
128            inner: Arc::new(ModelInner {
129                ptr: out,
130                compute_lock: Mutex::new(false),
131            }),
132        })
133    }
134
135    /// Open a session bound to this model with default session options.
136    pub fn session(&self) -> Result<Session> {
137        self.session_with(&SessionOptions::default())
138    }
139
140    /// Open a session bound to this model with explicit options.
141    pub fn session_with(&self, options: &SessionOptions) -> Result<Session> {
142        Session::new(self, options)
143    }
144
145    /// The model's immutable capabilities.
146    pub fn capabilities(&self) -> Capabilities {
147        let mut caps: sys::transcribe_capabilities = unsafe { std::mem::zeroed() };
148        unsafe { sys::transcribe_capabilities_init(&mut caps) };
149        // A NULL/struct-size fault cannot happen here (we own a valid model
150        // and an init'd struct), so a non-OK status leaves zeroed defaults.
151        let _ = unsafe { sys::transcribe_model_get_capabilities(self.inner.ptr, &mut caps) };
152
153        let mut languages = Vec::new();
154        if !caps.languages.is_null() && caps.n_languages > 0 {
155            let slice =
156                unsafe { std::slice::from_raw_parts(caps.languages, caps.n_languages as usize) };
157            for &lang in slice {
158                languages.push(owned_str(lang));
159            }
160        }
161
162        Capabilities {
163            native_sample_rate: caps.native_sample_rate,
164            languages,
165            max_timestamp_kind: TimestampKind::from_raw(caps.max_timestamp_kind),
166            supports_language_detect: caps.supports_language_detect,
167            supports_translate: caps.supports_translate,
168            supports_streaming: caps.supports_streaming,
169            supports_spec_decode: caps.supports_spec_decode,
170            max_audio_ms: caps.max_audio_ms,
171        }
172    }
173
174    /// Probe a yes/no feature.
175    pub fn supports(&self, feature: Feature) -> bool {
176        unsafe { sys::transcribe_model_supports(self.inner.ptr, feature.to_raw()) }
177    }
178
179    /// Whether this model accepts the given family-extension `kind` in `slot`.
180    pub fn accepts_ext(&self, slot: ExtSlot, kind: u32) -> bool {
181        unsafe { sys::transcribe_model_accepts_ext_kind(self.inner.ptr, slot.to_raw(), kind) }
182    }
183
184    /// The `general.architecture` string, e.g. "parakeet".
185    pub fn arch(&self) -> String {
186        owned_str(unsafe { sys::transcribe_model_arch_string(self.inner.ptr) })
187    }
188
189    /// The `stt.variant` string, e.g. "tdt-0.6b-v2" (may be empty).
190    pub fn variant(&self) -> String {
191        owned_str(unsafe { sys::transcribe_model_variant_string(self.inner.ptr) })
192    }
193
194    /// The runtime backend bound to this model, e.g. "cpu", "metal" — the way
195    /// to detect CPU fallback after requesting a GPU.
196    pub fn backend(&self) -> String {
197        owned_str(unsafe { sys::transcribe_model_backend(self.inner.ptr) })
198    }
199
200    /// Tokenize plain UTF-8 text into the model's vocabulary (no BOS/EOS, no
201    /// special tags). Errors with [`Error::NotImplemented`](crate::Error) for
202    /// families whose tokenizer has no encode path (e.g. SentencePiece today).
203    pub fn tokenize(&self, text: &str) -> Result<Vec<i32>> {
204        let c_text = CString::new(text)?;
205        // Grow-and-retry on the negative-N "buffer too small" signal.
206        let mut buf = vec![0i32; text.len().max(16)];
207        loop {
208            let n = unsafe {
209                sys::transcribe_tokenize(
210                    self.inner.ptr,
211                    c_text.as_ptr(),
212                    buf.as_mut_ptr(),
213                    buf.len(),
214                )
215            };
216            if n == i32::MIN {
217                return Err(crate::error::Error::NotImplemented(
218                    "model tokenizer has no encode path".to_string(),
219                ));
220            }
221            if n < 0 {
222                buf.resize((-n) as usize, 0);
223                continue;
224            }
225            buf.truncate(n as usize);
226            return Ok(buf);
227        }
228    }
229}
230
231fn check_model_load(status: sys::transcribe_status, context: &str) -> Result<()> {
232    #[cfg(feature = "dynamic-backends")]
233    {
234        if status == sys::transcribe_status::TRANSCRIBE_ERR_BACKEND
235            && crate::backend::device_count() == 0
236        {
237            let code = status.0 as i32;
238            let base = crate::error::status_string(code);
239            return Err(crate::error::Error::Backend(format!(
240                "{context}: {base} (status {code}); dynamic-backends builds \
241                 require backend modules to be loaded before model load. Call \
242                 transcribe_cpp::init_backends_default() when modules are \
243                 bundled next to libtranscribe, or init_backends(dir) for a \
244                 custom provider directory."
245            )));
246        }
247    }
248    check(status, context)
249}
250
251/// Options for creating a session.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct SessionOptions {
254    /// CPU threads for ops that run on CPU; 0 = library default.
255    pub n_threads: i32,
256    /// K/V activation precision.
257    pub kv_type: crate::types::KvType,
258    /// Optional decoder context cap in tokens; 0 = model maximum.
259    pub n_ctx: i32,
260}
261
262impl Default for SessionOptions {
263    fn default() -> Self {
264        SessionOptions {
265            n_threads: 0,
266            kv_type: crate::types::KvType::Auto,
267            n_ctx: 0,
268        }
269    }
270}
271
272/// Per-session effective limits.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub struct SessionLimits {
275    /// Decoder context cap in force for this session (0 = unbounded family).
276    pub effective_n_ctx: i32,
277    /// Longest accepted audio in ms (0 = no practical limit).
278    pub effective_max_audio_ms: i64,
279    /// Worst-case decoder KV bytes for one utterance (0 = no decoder KV).
280    pub max_kv_bytes: i64,
281}
282
283/// Convert a filesystem path to the bytes the C API's `const char *` expects.
284/// On Unix paths are arbitrary bytes, passed through verbatim; elsewhere the
285/// API takes UTF-8, so a non-UTF-8 path is rejected rather than lossily mangled
286/// (`to_string_lossy` would silently substitute U+FFFD). Shared with
287/// [`crate::backend::init_backends`].
288#[cfg(unix)]
289pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
290    use std::os::unix::ffi::OsStrExt;
291    Ok(path.as_os_str().as_bytes().to_vec())
292}
293
294#[cfg(not(unix))]
295pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
296    // The C API takes a UTF-8 `const char *`; require a UTF-8-representable path.
297    path.to_str().map(|s| s.as_bytes().to_vec()).ok_or_else(|| {
298        crate::error::Error::InvalidArgument(format!("non-UTF-8 path: {}", path.display()))
299    })
300}