Skip to main content

smriti/ml/
runtime.rs

1//! ONNX Runtime initialization and management
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Mutex, OnceLock};
6
7use ort::execution_providers::ExecutionProvider;
8use ort::session::builder::GraphOptimizationLevel;
9use ort::session::Session;
10
11/// Latch: only log the provider-probe result the first time a session is
12/// built. Subsequent sessions reuse whichever provider won without spamming.
13static EP_LOGGED: AtomicBool = AtomicBool::new(false);
14
15/// Successfully registered session providers. This is explicitly NOT a
16/// claim about GPU node placement; different models can use different providers.
17static ACTIVE_PROVIDER: Mutex<&'static str> = Mutex::new("Not initialized");
18#[cfg(target_os = "windows")]
19static WINDOWS_RUNTIME_LIBS: OnceLock<Vec<libloading::Library>> = OnceLock::new();
20static ORT_INITIALIZED: OnceLock<()> = OnceLock::new();
21static ORT_INIT_LOCK: Mutex<()> = Mutex::new(());
22
23/// User-facing label for the active execution provider, e.g. "DirectML",
24/// "CPU", or a qualified GPU-registration label. Uninitialized until a session succeeds.
25pub fn active_execution_provider() -> &'static str {
26    *ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner())
27}
28
29/// Platform-specific ONNX Runtime library name
30#[cfg(target_os = "windows")]
31const ORT_LIB_NAME: &str = "onnxruntime.dll";
32#[cfg(target_os = "macos")]
33const ORT_LIB_NAME: &str = "libonnxruntime.dylib";
34#[cfg(not(any(target_os = "windows", target_os = "macos")))]
35const ORT_LIB_NAME: &str = "libonnxruntime.so";
36
37/// ONNX Runtime environment wrapper
38///
39/// Manages the global ONNX Runtime environment and provides
40/// helper methods for loading models.
41///
42/// Uses `load-dynamic` feature: the runtime library is loaded at runtime.
43/// The library is resolved in this order:
44/// 1. `ORT_DYLIB_PATH` environment variable (if set)
45/// 2. `libs/onnxruntime/<LIB>` relative to the executable
46/// 3. `libs/onnxruntime/<LIB>` relative to the current working directory
47pub struct OnnxRuntime;
48
49impl OnnxRuntime {
50    fn usable_runtime_file(path: &Path) -> bool {
51        std::fs::metadata(path)
52            .is_ok_and(|metadata| metadata.is_file() && metadata.len() >= 1024 * 1024)
53    }
54
55    fn runtime_file_name_matches(name: &str) -> bool {
56        #[cfg(target_os = "macos")]
57        {
58            name.starts_with("libonnxruntime") && name.ends_with(".dylib")
59        }
60        #[cfg(not(target_os = "macos"))]
61        {
62            name.starts_with(ORT_LIB_NAME)
63        }
64    }
65
66    fn find_runtime_in_dir(dir: &Path) -> Option<PathBuf> {
67        let direct = dir.join(ORT_LIB_NAME);
68        if Self::usable_runtime_file(&direct) {
69            return Some(direct);
70        }
71
72        // Also check for versioned variants (e.g. libonnxruntime.so.1.23.0)
73        let entries = std::fs::read_dir(dir).ok()?;
74        for entry in entries.flatten() {
75            let path = entry.path();
76            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
77                if Self::runtime_file_name_matches(name) && Self::usable_runtime_file(&path) {
78                    return Some(path);
79                }
80            }
81        }
82
83        None
84    }
85
86    /// Resolve the path to the ONNX Runtime shared library.
87    ///
88    /// Checks ORT_DYLIB_PATH env var first, then looks in libs/onnxruntime/
89    /// relative to the executable and current working directory.
90    fn resolve_dylib_path() -> Option<PathBuf> {
91        // 1. Check ORT_DYLIB_PATH environment variable
92        if let Ok(path) = std::env::var("ORT_DYLIB_PATH") {
93            let p = PathBuf::from(&path);
94            if p.exists() {
95                tracing::info!("Using ONNX Runtime from ORT_DYLIB_PATH: {}", p.display());
96                return Some(p);
97            }
98            tracing::warn!("ORT_DYLIB_PATH set but file not found: {}", path);
99        }
100
101        // 1b. Check installed optional asset-pack roots. The asset pack
102        // stores runtimes under platform subdirectories; bootstrap owns
103        // that layout so health checks and dynamic loading agree.
104        if let Some(candidate) = crate::bootstrap::onnx_runtime_path() {
105            tracing::info!(
106                "Using ONNX Runtime from optional asset-pack path: {}",
107                candidate.display()
108            );
109            return Some(candidate);
110        }
111
112        let rel_dir = Path::new("libs").join("onnxruntime");
113
114        // 2. Relative to the executable. Also tries two levels up
115        // because `cargo tauri dev` runs the binary from
116        // `target/debug/`, and the dev-tree `libs/onnxruntime/` lives
117        // at the workspace root (target/debug/../.. = workspace).
118        if let Ok(exe) = std::env::current_exe() {
119            if let Some(exe_dir) = exe.parent() {
120                for base in [exe_dir.to_path_buf(), exe_dir.join("..").join("..")] {
121                    let candidate_dir = base.join(&rel_dir);
122                    if let Some(candidate) = Self::find_runtime_in_dir(&candidate_dir) {
123                        tracing::info!(
124                            "Using ONNX Runtime from exe-relative path: {}",
125                            candidate.display()
126                        );
127                        return Some(candidate);
128                    }
129                }
130            }
131        }
132
133        // 3. Relative to the current working directory. Also walks one
134        // level up because `cargo tauri dev` sets CWD to src-tauri/,
135        // not the workspace root.
136        if let Ok(cwd) = std::env::current_dir() {
137            let mut bases: Vec<PathBuf> = vec![cwd.clone()];
138            if let Some(parent) = cwd.parent() {
139                bases.push(parent.to_path_buf());
140            }
141            for base in bases {
142                let candidate_dir = base.join(&rel_dir);
143                if let Some(candidate) = Self::find_runtime_in_dir(&candidate_dir) {
144                    tracing::info!(
145                        "Using ONNX Runtime from cwd-relative path: {}",
146                        candidate.display()
147                    );
148                    return Some(candidate);
149                }
150            }
151        }
152
153        None
154    }
155
156    /// Initialize the ONNX Runtime global environment.
157    ///
158    /// Dynamically loads libonnxruntime.so at runtime. The library is searched
159    /// in the order described on [`OnnxRuntime`].
160    ///
161    /// This should be called once at application startup, before creating any sessions.
162    pub fn init() -> ort::Result<Self> {
163        if ORT_INITIALIZED.get().is_some() {
164            return Ok(Self);
165        }
166
167        let _guard = ORT_INIT_LOCK.lock().map_err(|_| {
168            ort::Error::new("ONNX Runtime initialization lock is poisoned".to_string())
169        })?;
170        if ORT_INITIALIZED.get().is_some() {
171            return Ok(Self);
172        }
173
174        if let Some(dylib_path) = Self::resolve_dylib_path() {
175            #[cfg(target_os = "windows")]
176            if WINDOWS_RUNTIME_LIBS.get().is_none() {
177                use libloading::os::windows::{
178                    Library, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR,
179                };
180                let root = dylib_path
181                    .parent()
182                    .ok_or_else(|| ort::Error::new("Runtime path has no parent"))?;
183                let mut libraries = Vec::new();
184                for dependency in [
185                    "DirectML.dll",
186                    "onnxruntime_providers_shared.dll",
187                    ORT_LIB_NAME,
188                ] {
189                    let path = root.join(dependency);
190                    if !path.is_file() {
191                        continue;
192                    } // Standard CPU installations remain supported.
193                      // SAFETY: load only runtime assets beside the selected ORT DLL.
194                      // Keep handles alive for all sessions; dependency search is restricted
195                      // to that directory and Windows' safe default directories.
196                    let library = unsafe {
197                        Library::load_with_flags(
198                            &path,
199                            LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
200                        )
201                    }
202                    .map_err(|e| {
203                        ort::Error::new(format!("Failed loading {}: {e}", path.display()))
204                    })?;
205                    libraries.push(library.into());
206                }
207                let _ = WINDOWS_RUNTIME_LIBS.set(libraries);
208            }
209            ort::init_from(&dylib_path)?.commit();
210            let _ = ORT_INITIALIZED.set(());
211            tracing::info!(
212                "ONNX Runtime initialized (dynamic) from: {}",
213                dylib_path.display()
214            );
215        } else {
216            return Err(ort::Error::new(
217                format!(
218                    "ONNX Runtime library not found. Set ORT_DYLIB_PATH or place {} (1.23.x) in libs/onnxruntime/",
219                    ORT_LIB_NAME
220                ),
221            ));
222        }
223        Ok(Self)
224    }
225
226    /// Load an ONNX model with a specific number of intra-op threads.
227    ///
228    /// Attempts to register GPU execution providers in platform-specific
229    /// priority order, then falls back to CPU if none initialize. The CPU
230    /// provider is always appended last so session creation never fails due
231    /// to missing GPU drivers or runtime libraries.
232    ///
233    /// Platform priority:
234    ///   Windows: DirectML  (covers NVIDIA/AMD/Intel/Qualcomm via D3D12)
235    ///   Linux:   CUDA      (NVIDIA). ROCm could be added via a cargo flag later.
236    ///   macOS:   CoreML    (Apple Silicon + AMD on Intel Macs)
237    ///
238    /// `intra_threads` applies to the CPU provider; GPU providers ignore it.
239    pub fn load_model_with_threads<P: AsRef<Path>>(
240        &self,
241        path: P,
242        intra_threads: usize,
243    ) -> ort::Result<Session> {
244        // Registration failure must be observable: try complete sessions one at
245        // a time, then retry CPU if a GPU cannot initialize this particular model.
246        let path = path.as_ref();
247        let providers = vec![
248            #[cfg(target_os = "windows")]
249            (
250                "DirectML registered (placement unverified)",
251                ort::execution_providers::DirectMLExecutionProvider::default().build(),
252            ),
253            #[cfg(target_os = "linux")]
254            (
255                "CUDA registered (placement unverified)",
256                ort::execution_providers::CUDAExecutionProvider::default().build(),
257            ),
258            #[cfg(target_os = "linux")]
259            (
260                "OpenVINO registered (placement unverified)",
261                ort::execution_providers::OpenVINO::default()
262                    .with_device_type("GPU")
263                    .build(),
264            ),
265            #[cfg(target_os = "macos")]
266            (
267                "CoreML registered (placement unverified)",
268                ort::execution_providers::CoreMLExecutionProvider::default().build(),
269            ),
270            (
271                "CPU",
272                ort::execution_providers::CPUExecutionProvider::default().build(),
273            ),
274        ];
275
276        if !EP_LOGGED.swap(true, Ordering::Relaxed) {
277            Self::probe_and_log_providers();
278        }
279        let mut last_error = None;
280        for (label, provider) in providers {
281            let attempt = (|| {
282                let builder = Session::builder()?
283                    .with_optimization_level(GraphOptimizationLevel::Level3)?
284                    .with_intra_threads(intra_threads.clamp(1, 2))?
285                    .with_parallel_execution(false)?
286                    .with_config_entry("session.intra_op.allow_spinning", "0")?
287                    .with_config_entry("session.inter_op.allow_spinning", "0")?;
288                let builder = if label.starts_with("DirectML") {
289                    builder.with_memory_pattern(false)?
290                } else {
291                    builder
292                };
293                builder
294                    .with_execution_providers([provider.error_on_failure()])?
295                    .commit_from_file(path)
296            })();
297            match attempt {
298                Ok(session) => {
299                    let mut active = ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner());
300                    *active = if *active == "Not initialized" || *active == label {
301                        label
302                    } else {
303                        "Mixed model providers (see logs; placement unverified)"
304                    };
305                    tracing::info!(model = %path.display(), provider = label, "Inference session initialized");
306                    return Ok(session);
307                }
308                Err(error) => {
309                    tracing::warn!(model = %path.display(), provider = label, %error,
310                        "Provider initialization failed; trying fallback");
311                    last_error = Some(error);
312                }
313            }
314        }
315        Err(last_error.expect("CPU provider is always attempted"))
316    }
317
318    /// A one-way CPU fallback after an inference-time provider/device failure.
319    pub fn load_cpu_model(path: &Path) -> ort::Result<Session> {
320        let session = Self::load_cpu_model_with_threads(path, 1)?;
321        *ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner()) =
322            "CPU fallback used (see per-model logs)";
323        tracing::warn!(model = %path.display(), "Inference moved to CPU after device/provider failure");
324        Ok(session)
325    }
326
327    /// Build a CPU-only session with an explicit share of the aggregate face
328    /// processing budget. Face workers use this path because constructing one
329    /// DirectML session per worker caused severe cold-start and throughput
330    /// regressions on integrated GPUs. Other ML features may still use the
331    /// provider-selecting path above.
332    pub fn load_cpu_model_with_threads(path: &Path, intra_threads: usize) -> ort::Result<Session> {
333        let session = Session::builder()?
334            .with_optimization_level(GraphOptimizationLevel::Level3)?
335            .with_intra_threads(intra_threads.max(1))?
336            .with_parallel_execution(false)?
337            .with_config_entry("session.intra_op.allow_spinning", "0")?
338            .with_config_entry("session.inter_op.allow_spinning", "0")?
339            .with_execution_providers([ort::execution_providers::CPUExecutionProvider::default()
340                .build()
341                .error_on_failure()])?
342            .commit_from_file(path)?;
343        let mut active = ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner());
344        *active = if *active == "Not initialized" || *active == "CPU" {
345            "CPU"
346        } else {
347            "Mixed model providers (see logs; placement unverified)"
348        };
349        tracing::info!(model = %path.display(), threads = intra_threads.max(1), "CPU inference session initialized");
350        Ok(session)
351    }
352
353    /// Load a latency-sensitive CPU model without the expensive offline-style
354    /// graph rewrites used by long-running batch inference. This is the right
355    /// tradeoff for semantic text search: the session must become available
356    /// quickly, while each interaction runs only one tiny text input.
357    pub fn load_cpu_model_for_interactive(path: &Path) -> ort::Result<Session> {
358        let session = Session::builder()?
359            .with_optimization_level(GraphOptimizationLevel::Level1)?
360            .with_intra_threads(1)?
361            .with_parallel_execution(false)?
362            .with_config_entry("session.intra_op.allow_spinning", "0")?
363            .with_config_entry("session.inter_op.allow_spinning", "0")?
364            .with_execution_providers([ort::execution_providers::CPUExecutionProvider::default()
365                .build()
366                .error_on_failure()])?
367            .commit_from_file(path)?;
368        tracing::info!(model = %path.display(), "Interactive CPU inference session initialized");
369        Ok(session)
370    }
371
372    /// One-shot probe: log which execution providers are usable on this
373    /// machine, and say plainly which of them this build will actually use.
374    ///
375    /// Two things this deliberately does NOT claim:
376    ///
377    /// 1. That face detection/embedding will use a GPU. It will not —
378    ///    `FaceDetector`/`FaceEmbedder` both call
379    ///    `load_cpu_model_with_threads`, because building one DirectML session
380    ///    per worker caused severe cold-start and throughput regressions on
381    ///    integrated GPUs. Only the provider-selecting path (semantic search)
382    ///    still probes for a GPU, so the log says so instead of implying faces
383    ///    are GPU-bound.
384    fn probe_and_log_providers() {
385        let mut accelerated: Vec<&'static str> = Vec::new();
386
387        #[cfg(target_os = "windows")]
388        {
389            let ep = ort::execution_providers::DirectMLExecutionProvider::default();
390            if ep.is_available().unwrap_or(false) {
391                accelerated.push("DirectML");
392            }
393        }
394
395        #[cfg(target_os = "linux")]
396        {
397            let ep = ort::execution_providers::CUDAExecutionProvider::default();
398            if ep.is_available().unwrap_or(false) {
399                accelerated.push("CUDA");
400            }
401
402            let ep = ort::execution_providers::OpenVINO::default();
403            if ep.is_available().unwrap_or(false) {
404                accelerated.push("OpenVINO");
405            }
406        }
407
408        #[cfg(target_os = "macos")]
409        {
410            let ep = ort::execution_providers::CoreMLExecutionProvider::default();
411            if ep.is_available().unwrap_or(false) {
412                accelerated.push("CoreML");
413            }
414        }
415
416        tracing::info!(
417            accelerated = %if accelerated.is_empty() { "none".to_string() } else { accelerated.join(", ") },
418            "Execution providers present. Face detection/embedding always run on CPU; \
419             the provider-selecting path (semantic search) tries accelerated providers first, \
420             then CPU."
421        );
422    }
423}