Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: set backend path environment variables for llama.cpp (#6937)
Akarshan Biswas2af5ab956670
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex 69062f755..c9483e116 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -9,47 +9,45 @@ import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'* This is used for migrating stored user preferences.*/export function mapOldBackendToNew(oldBackend: string): string {- const isWindows = oldBackend.startsWith('win-')- const isLinux = oldBackend.startsWith('linux-')- const osPrefix = isWindows ? 'win-' : isLinux ? 'linux-' : ''-- // Determine architecture suffix, defaulting to x64- const archSuffix = oldBackend.includes('-arm64') ? 'arm64' : 'x64'- const isX64 = archSuffix === 'x64'-- // Handle GPU backends- if (oldBackend.includes('cuda-cu12.0')) {- // Migration from e.g., 'linux-avx2-cuda-cu12.0-x64' to 'linux-cuda-12-common_cpus-x64'- return `${osPrefix}cuda-12-common_cpus-${isX64 ? 'x64' : archSuffix}`- } else if (oldBackend.includes('cuda-cu11.7')) {- // Migration from e.g., 'win-noavx-cuda-cu11.7-x64' to 'win-cuda-11-common_cpus-x64'- return `${osPrefix}cuda-11-common_cpus-${isX64 ? 'x64' : archSuffix}`- } else if (oldBackend.includes('vulkan')) {- // If it's already the new name, return it- if (oldBackend.includes('vulkan-common_cpus')) return oldBackend-- // Migration from e.g., 'linux-vulkan-x64' to 'linux-vulkan-common_cpus-x64'- return `${osPrefix}vulkan-common_cpus-${isX64 ? 'x64' : archSuffix}`- }+ const isWindows = oldBackend.startsWith('win-')+ const isLinux = oldBackend.startsWith('linux-')+ const osPrefix = isWindows ? 'win-' : isLinux ? 'linux-' : ''++ // Determine architecture suffix, defaulting to x64+ const archSuffix = oldBackend.includes('-arm64') ? 'arm64' : 'x64'+ const isX64 = archSuffix === 'x64'++ // Handle GPU backends+ if (oldBackend.includes('cuda-cu12.0')) {+ // Migration from e.g., 'linux-avx2-cuda-cu12.0-x64' to 'linux-cuda-12-common_cpus-x64'+ return `${osPrefix}cuda-12-common_cpus-${isX64 ? 'x64' : archSuffix}`+ } else if (oldBackend.includes('cuda-cu11.7')) {+ // Migration from e.g., 'win-noavx-cuda-cu11.7-x64' to 'win-cuda-11-common_cpus-x64'+ return `${osPrefix}cuda-11-common_cpus-${isX64 ? 'x64' : archSuffix}`+ } else if (oldBackend.includes('vulkan')) {+ // If it's already the new name, return it+ if (oldBackend.includes('vulkan-common_cpus')) return oldBackend++ // Migration from e.g., 'linux-vulkan-x64' to 'linux-vulkan-common_cpus-x64'+ return `${osPrefix}vulkan-common_cpus-${isX64 ? 'x64' : archSuffix}`+ }- // Handle CPU-only backends (avx, avx2, avx512, noavx)- const isOldCpuBackend =- oldBackend.includes('avx512') ||- oldBackend.includes('avx2') ||- oldBackend.includes('avx-x64') || // Check for 'avx' but not as part of 'avx2' or 'avx512'- oldBackend.includes('noavx-x64')+ // Handle CPU-only backends (avx, avx2, avx512, noavx)+ const isOldCpuBackend =+ oldBackend.includes('avx512') ||+ oldBackend.includes('avx2') ||+ oldBackend.includes('avx-x64') || // Check for 'avx' but not as part of 'avx2' or 'avx512'+ oldBackend.includes('noavx-x64')- if (isOldCpuBackend) {- // Migration from e.g., 'win-avx512-x64' to 'win-common_cpus-x64'- return `${osPrefix}common_cpus-${isX64 ? 'x64' : archSuffix}`- }+ if (isOldCpuBackend) {+ // Migration from e.g., 'win-avx512-x64' to 'win-common_cpus-x64'+ return `${osPrefix}common_cpus-${isX64 ? 'x64' : archSuffix}`+ }- // Return original if it doesn't match a pattern that needs migration (e.g., macos/arm64 which are already 'common')- return oldBackend+ // Return original if it doesn't match a pattern that needs migration (e.g., macos/arm64 which are already 'common')+ return oldBackend}--/** Reads currently installed backends in janDataFolderPath*@@ -127,8 +125,8 @@ async function fetchRemoteSupportedBackends(}const mappedNew = mapOldBackendToNew(backend)if (mappedNew !== backend && supportedBackends.includes(mappedNew)) {- // Push the ORIGINAL backend name here, as this is the name of the file on the server.- remote.push({ version, backend })+ // Push the ORIGINAL backend name here, as this is the name of the file on the server.+ remote.push({ version, backend })}}}@@ -170,10 +168,10 @@ export async function listSupportedBackends(): Promise<} else if (sysType === 'linux-x86_64' || sysType === 'linux-x86') {supportedBackends.push('linux-common_cpus-x64')if (features.cuda11) {- supportedBackends.push('linux-cuda-11-common_cpus-x64')+ supportedBackends.push('linux-cuda-11-common_cpus-x64')}if (features.cuda12) {- supportedBackends.push('linux-cuda-12-common_cpus-x64')+ supportedBackends.push('linux-cuda-12-common_cpus-x64')}if (features.vulkan) supportedBackends.push('linux-vulkan-common_cpus-x64')}@@ -189,9 +187,11 @@ export async function listSupportedBackends(): Promise<let remoteBackendVersions = []try {remoteBackendVersions =- await fetchRemoteSupportedBackends(supportedBackends)+ await fetchRemoteSupportedBackends(supportedBackends)} catch (e) {- console.debug(`Not able to get remote backends, Jan might be offline or network problem: ${String(e)}`)+ console.debug(+ `Not able to get remote backends, Jan might be offline or network problem: ${String(e)}`+ )}// Get locally installed versions@@ -286,7 +286,10 @@ export async function downloadBackend(]// also download CUDA runtime + cuBLAS + cuBLASLt if needed- if (backend.includes('cu11.7') && !(await _isCudaInstalled('11.7'))) {+ if (+ backend.includes('cu11.7') &&+ !(await _isCudaInstalled(backendDir, '11.7'))+ ) {downloadItems.push({url:source === 'github'@@ -295,7 +298,10 @@ export async function downloadBackend(save_path: await joinPath([backendDir, 'build', 'bin', 'cuda11.tar.gz']),proxy: proxyConfig,})- } else if (backend.includes('cu12.0') && !(await _isCudaInstalled('12.0'))) {+ } else if (+ backend.includes('cu12.0') &&+ !(await _isCudaInstalled(backendDir, '12.0'))+ ) {downloadItems.push({url:source === 'github'@@ -427,17 +433,20 @@ async function _fetchGithubReleases(}}-async function _isCudaInstalled(version: string): Promise<boolean> {+// accept backendDir (full path) and cuda version (e.g. '11.7' or '12.0')+async function _isCudaInstalled(+ backendDir: string,+ version: string+): Promise<boolean> {const sysInfo = await getSystemInfo()- const os_type = sysInfo.os_type-- // not sure the reason behind this naming convention+ const os_type = sysInfo.os_type // not sure the reason behind this naming conventionconst libnameLookup = {'windows-11.7': `cudart64_110.dll`,'windows-12.0': `cudart64_12.dll`,'linux-11.7': `libcudart.so.11.0`,'linux-12.0': `libcudart.so.12`,}+const key = `${os_type}-${version}`if (!(key in libnameLookup)) {return false@@ -445,29 +454,37 @@ async function _isCudaInstalled(version: string): Promise<boolean> {const libname = libnameLookup[key]- // check from system libraries first- // TODO: might need to check for CuBLAS and CuBLASLt as well- if (os_type === 'linux') {- // not sure why libloading cannot find library from name alone- // using full path here- const libPath = `/usr/local/cuda/lib64/${libname}`- if (await invoke<boolean>('is_library_available', { library: libPath }))- return true- } else if (os_type === 'windows') {- // TODO: test this on Windows- if (await invoke<boolean>('is_library_available', { library: libname }))- return true- }+ // Expected new location+ const newPath = await joinPath([backendDir, 'build', 'bin', libname])+ if (await fs.existsSync(newPath)) return true- // check for libraries shipped with Jan's llama.cpp extension+ // Old location (used by older builds)const janDataFolderPath = await getJanDataFolderPath()- const cudartPath = await joinPath([+ const oldPath = await joinPath([janDataFolderPath,'llamacpp','lib',libname,])- return await fs.existsSync(cudartPath)++ if (await fs.existsSync(oldPath)) {+ // Ensure target directory exists+ const targetDir = await joinPath([backendDir, 'build', 'bin'])+ if (!(await fs.existsSync(targetDir))) {+ await fs.mkdir(targetDir, { recursive: true })+ }++ try {+ // Move old lib to the correct new location+ await fs.mv(oldPath, newPath)+ console.log(`[CUDA] Migrated ${libname} from old path to new location.`)+ return true+ } catch (err) {+ console.warn(`[CUDA] Failed to move old library:`, err)+ }+ }++ return false}function compareVersions(a: string, b: string): number {diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 614eeaa02..6fafbab20 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -26,7 +26,6 @@ import {import { error, info, warn } from '@tauri-apps/plugin-log'import { listen } from '@tauri-apps/api/event'-import {listSupportedBackends,downloadBackend,@@ -659,16 +658,19 @@ export default class llamacpp_extension extends AIEngine {await new Promise((resolve) => setTimeout(resolve, 1000))}+ const effectiveBackendType = mapOldBackendToNew(backend)+ const currentStoredBackend = this.getStoredBackendType()++ targetBackendString = `${version}/${effectiveBackendType}`+// Update configurationthis.config.version_backend = targetBackendString// Store the backend type preference only if it changed- const effectiveBackendType = mapOldBackendToNew(backend)- const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== effectiveBackendType) {- this.setStoredBackendType(effectiveBackendType)+ if (currentStoredBackend !== targetBackendString) {+ this.setStoredBackendType(targetBackendString)logger.info(- `Updated stored backend type preference: ${effectiveBackendType}`+ `Updated stored backend type preference: ${targetBackendString}`)}@@ -760,13 +762,13 @@ export default class llamacpp_extension extends AIEngine {if (!targetBackendString) {logger.warn(- `No available versions found for current backend type: ${currentBackend}`+ `No available versions found for current backend type: ${currentEffectiveBackendType}`)// Attempt to fall back to the absolute best available if the preferred type is gone.- if (- currentBackend !==- mapOldBackendToNew(bestAvailableBackendString.split('/')[1])- ) {+ const bestEffectiveType = mapOldBackendToNew(+ bestAvailableBackendString.split('/')[1]+ )+ if (currentEffectiveBackendType !== bestEffectiveType) {logger.info(`Falling back to best available backend: ${bestAvailableBackendString}`)@@ -777,17 +779,18 @@ export default class llamacpp_extension extends AIEngine {const [latestVersion, latestBackendName] = targetBackendString.split('/')- // Check if update is needed (only version comparison for same backend type)+ // Check if update is needed (compare versions AND effective backend types)if (currentVersion === latestVersion &&- currentBackend === latestBackendName+ currentEffectiveBackendType === mapOldBackendToNew(latestBackendName)) {logger.info('Auto-update: Already using the latest version of the selected backend')return { wasUpdated: false, newBackend: this.config.version_backend }}- // Perform version update for the same backend type++ // Perform version update or migration for the same effective backend typelogger.info(`Auto-updating/Migrating from ${this.config.version_backend} to ${targetBackendString} (preserving effective backend type: ${currentEffectiveBackendType})`)@@ -804,6 +807,7 @@ export default class llamacpp_extension extends AIEngine {async checkBackendForUpdates(): Promise<{updateNeeded: booleannewVersion: string+ targetBackend?: string}> {// Parse current backend configurationconst [currentVersion, currentBackend] = (@@ -817,19 +821,38 @@ export default class llamacpp_extension extends AIEngine {return { updateNeeded: false, newVersion: '0' }}- // Find the latest version for the currently selected backend type+ // Get the effective/migrated backend type for consistency with auto-update logic+ const currentEffectiveBackendType = mapOldBackendToNew(currentBackend)++ // Find the latest version for the currently selected backend type (using effective type)const version_backends = await listSupportedBackends()const targetBackendString = this.findLatestVersionForBackend(version_backends,- currentBackend+ currentEffectiveBackendType // Use the effective type)- const [latestVersion] = targetBackendString.split('/')++ if (!targetBackendString) {+ logger.warn(+ `No available versions found for current backend type: ${currentEffectiveBackendType}`+ )+ return { updateNeeded: false, newVersion: '0' }+ }++ const [latestVersion, latestBackend] = targetBackendString.split('/')++ // Check if update is needed (version comparison)if (this.parseBackendVersion(latestVersion) >this.parseBackendVersion(currentVersion)) {- logger.info(`New update available: ${latestVersion}`)- return { updateNeeded: true, newVersion: latestVersion }+ logger.info(+ `New update available: ${latestVersion} -> ${targetBackendString}`+ )+ return {+ updateNeeded: true,+ newVersion: latestVersion,+ targetBackend: targetBackendString,+ }} else {logger.info(`Already at latest version: ${currentVersion} = ${latestVersion}`@@ -958,10 +981,16 @@ export default class llamacpp_extension extends AIEngine {// Store the backend type preference in localStorage only if it changedif (backend) {+ // Use the effective/migrated backend type for storage+ const effectiveBackendType = mapOldBackendToNew(backend)const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== backend) {- this.setStoredBackendType(backend)- logger.info(`Updated backend type preference to: ${backend}`)++ // Compare with the effective type+ if (currentStoredBackend !== effectiveBackendType) {+ this.setStoredBackendType(effectiveBackendType)+ logger.info(+ `Updated backend type preference to: ${effectiveBackendType}`+ )}}@@ -1175,11 +1204,13 @@ export default class llamacpp_extension extends AIEngine {async installBackend(path: string): Promise<void> {const platformName = IS_WINDOWS ? 'win' : 'linux'- // Match any prefix before 'llama', then version and backend+ // Match prefix (optional), llama, main (optional), version (b####-hash),+ // optional cudart-llama, bin, backend details// Examples:- // - llama-b6929-bin-<os>-<backend>-x64.tar.gz or zip- // - custom-prefix-llama-b6929-bin-<os>-<backend>-x64.tar.gz or zip- const re = /^(.+?-)?llama-(b\d+)-bin-(.+?)\.(?:tar\.gz|zip)$/+ // - k_llama-main-b4314-09c61e1-bin-win-cuda-12.8-x64-avx2.zip+ // - ik_llama-main-b4314-09c61e1-cudart-llama-bin-win-cuda-12.8-x64-avx512.zip+ // - llama-b7037-bin-win-cuda-12.4-x64.zip (legacy format)+ const re = /^(.+?[-_])?llama(?:-main)?-(b\d+(?:-[a-f0-9]+)?)(?:-cudart-llama)?-bin-(.+?)\.(?:tar\.gz|zip)$/const archiveName = await basename(path)logger.info(`Installing backend from path: ${path}`)@@ -2117,11 +2148,10 @@ export default class llamacpp_extension extends AIEngine {await this.ensureBackendReady(backend, version)logger.info('Calling Tauri command getDevices with arg --list-devices')const backendPath = await getBackendExePath(backend, version)- const libraryPath = await joinPath([await this.getProviderPath(), 'lib'])+try {const dList = await invoke<DeviceList[]>('plugin:llamacpp|get_devices', {backendPath,- libraryPath,envs,})// On Linux with AMD GPUs, llama.cpp via Vulkan may report UMA (shared) memory as device-local.diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex a53661f23..da998bad9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -19,7 +19,8 @@ use crate::process::{};use crate::state::{LLamaBackendSession, LlamacppState, SessionInfo};use jan_utils::{- extract_arg_value, parse_port_from_args, setup_library_path, setup_windows_process_flags,+ add_cuda_paths, binary_requires_cuda, extract_arg_value, parse_port_from_args,+ setup_library_path, setup_windows_process_flags,};#[cfg(unix)]@@ -87,14 +88,26 @@ pub async fn load_llama_model<R: Runtime>(// Configure the command to run the serverlet mut command = Command::new(&bin_path);+command.args(args);command.envs(envs);- setup_library_path(bin_path.parent().and_then(|p| p.to_str()), &mut command);command.stdout(Stdio::piped());command.stderr(Stdio::piped());setup_windows_process_flags(&mut command);+ // Try to add CUDA paths (works on both Windows and Linux)+ let cuda_found = add_cuda_paths(&mut command);++ // Optionally check if binary needs CUDA+ if !cuda_found && binary_requires_cuda(&bin_path) {+ log::warn!(+ "llama.cpp backend appears to require CUDA, but CUDA not found. Process may fail to start. Please install cuda runtime and try again!"+ );+ }++ // Add the binary's directory to library path+ setup_library_path(bin_path.parent(), &mut command);// Spawn the child processlet mut child = command.spawn().map_err(ServerError::Io)?;diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rsindex 922e70c14..1366fbf65 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs@@ -7,7 +7,7 @@ use tokio::time::timeout;use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};use crate::path::validate_binary_path;-use jan_utils::{setup_library_path, setup_windows_process_flags};+use jan_utils::{add_cuda_paths, binary_requires_cuda, setup_library_path, setup_windows_process_flags};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct DeviceInfo {@@ -30,13 +30,21 @@ pub async fn get_devices_from_backend(command.arg("--list-devices");command.envs(envs);- // Set up library path- setup_library_path(bin_path.parent().and_then(|p| p.to_str()), &mut command);-command.stdout(Stdio::piped());command.stderr(Stdio::piped());-setup_windows_process_flags(&mut command);+ // Try to add CUDA paths (works on both Windows and Linux)+ let cuda_found = add_cuda_paths(&mut command);++ // Optionally check if binary needs CUDA+ if !cuda_found && binary_requires_cuda(&bin_path) {+ log::warn!(+ "llama.cpp backend appears to require CUDA, but CUDA not found. Process may fail to start. Please install cuda runtime and try again!"+ );+ }++ // Add the binary's directory to library path+ setup_library_path(bin_path.parent(), &mut command);// Execute the command and wait for completionlet output = timeout(Duration::from_secs(30), command.output())@@ -275,7 +283,7 @@ mod tests {fn test_find_memory_pattern_no_match() {let text = "No memory info here";assert!(find_memory_pattern(text).is_none());-+let text_with_invalid = "Some text (invalid memory info) here";assert!(find_memory_pattern(text_with_invalid).is_none());}diff --git a/src-tauri/utils/src/system.rs b/src-tauri/utils/src/system.rsindex efb137550..8e2e75cda 100644--- a/src-tauri/utils/src/system.rs+++ b/src-tauri/utils/src/system.rs@@ -1,3 +1,5 @@+use std::path::Path;+/// Checks if npx can be overridden with bun binarypub fn can_override_npx(bun_path: String) -> bool {// We need to check the CPU for the AVX2 instruction support if we are running under MacOS@@ -39,42 +41,302 @@ pub fn can_override_uvx(uv_path: String) -> bool {}/// Setup library paths for different operating systems-pub fn setup_library_path(library_path: Option<&str>, command: &mut tokio::process::Command) {+pub fn setup_library_path(library_path: Option<&Path>, command: &mut tokio::process::Command) {if let Some(lib_path) = library_path {if cfg!(target_os = "linux") {+ let lib_str = lib_path.to_string_lossy();let new_lib_path = match std::env::var("LD_LIBRARY_PATH") {- Ok(path) => format!("{}:{}", path, lib_path),- Err(_) => lib_path.to_string(),+ Ok(path) => format!("{}:{}", lib_str, path),+ Err(_) => lib_str.to_string(),};command.env("LD_LIBRARY_PATH", new_lib_path);++ #[cfg(feature = "logging")]+ log::info!("Added to LD_LIBRARY_PATH: {}", lib_str);} else if cfg!(target_os = "windows") {+ let lib_str = lib_path.to_string_lossy();++ // Normalize UNC prefix+ let normalized_str = if lib_str.starts_with(r"\\?\") {+ &lib_str[4..]+ } else {+ lib_str.as_ref()+ };+let new_path = match std::env::var("PATH") {- Ok(path) => format!("{};{}", path, lib_path),- Err(_) => lib_path.to_string(),+ Ok(path) => format!("{};{}", normalized_str, path),+ Err(_) => normalized_str.to_string(),};- command.env("PATH", new_path);+ command.env("PATH", &new_path);- // Normalize the path by removing UNC prefix if present- let normalized_path = lib_path.trim_start_matches(r"\\?\").to_string();#[cfg(feature = "logging")]- log::info!("Library path:\n{}", &normalized_path);+ log::info!("Added to PATH: {}", normalized_str);- // Only set current_dir if the normalized path exists and is a directory- let path = std::path::Path::new(&normalized_path);- if path.exists() && path.is_dir() {- command.current_dir(&normalized_path);- } else {- #[cfg(feature = "logging")]- log::warn!(- "Library path '{}' does not exist or is not a directory",- normalized_path- );- }+ command.current_dir(lib_path);+ } else if cfg!(target_os = "macos") {+ let lib_str = lib_path.to_string_lossy();+ let new_lib_path = match std::env::var("DYLD_LIBRARY_PATH") {+ Ok(path) => format!("{}:{}", lib_str, path),+ Err(_) => lib_str.to_string(),+ };+ command.env("DYLD_LIBRARY_PATH", new_lib_path);++ #[cfg(feature = "logging")]+ log::info!("Added to DYLD_LIBRARY_PATH: {}", lib_str);} else {#[cfg(feature = "logging")]- log::warn!("Library path setting is not supported on this OS");+ log::warn!("Library path setup not supported on this OS");+ }+ }+}++pub fn binary_requires_cuda(bin_path: &Path) -> bool {+ #[cfg(target_os = "windows")]+ return binary_requires_cuda_windows(bin_path);++ #[cfg(target_os = "linux")]+ return binary_requires_cuda_linux(bin_path);++ #[cfg(not(any(target_os = "windows", target_os = "linux")))]+ false+}++#[cfg(target_os = "windows")]+fn binary_requires_cuda_windows(bin_path: &Path) -> bool {+ // Check if the binary imports CUDA DLLs+ // This is a simplified check - looks for common CUDA DLL names in the binary+ if let Ok(contents) = std::fs::read(bin_path) {+ let contents_str = String::from_utf8_lossy(&contents);+ return contents_str.contains("cudart")+ || contents_str.contains("cublas")+ || contents_str.contains("cufft")+ || contents_str.contains("curand")+ || contents_str.contains("cusparse")+ || contents_str.contains("cusolver")+ || contents_str.contains("cudnn");+ }+ false+}++#[cfg(target_os = "linux")]+fn binary_requires_cuda_linux(bin_path: &Path) -> bool {+ // Use 'ldd' to check for CUDA library dependencies+ // This is more reliable than string searching+ if let Ok(output) = std::process::Command::new("ldd").arg(bin_path).output() {+ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout);+ return stdout.contains("libcudart")+ || stdout.contains("libcublas")+ || stdout.contains("libcufft")+ || stdout.contains("libcurand")+ || stdout.contains("libcusparse")+ || stdout.contains("libcusolver")+ || stdout.contains("libcudnn");+ }+ }++ // Fallback: simple string search in binary (less reliable on Linux)+ if let Ok(contents) = std::fs::read(bin_path) {+ let contents_str = String::from_utf8_lossy(&contents);+ return contents_str.contains("libcudart")+ || contents_str.contains("libcublas")+ || contents_str.contains("libcufft");+ }++ false+}++/// Adds CUDA paths to the command's environment based on the OS.+pub fn add_cuda_paths(command: &mut tokio::process::Command) -> bool {+ #[cfg(target_os = "windows")]+ return add_cuda_paths_windows(command);++ #[cfg(target_os = "linux")]+ return add_cuda_paths_linux(command);++ #[cfg(not(any(target_os = "windows", target_os = "linux")))]+ {+ #[cfg(feature = "logging")]+ log::debug!("CUDA path detection not implemented for this OS");+ false+ }+}++#[cfg(target_os = "windows")]+pub fn add_cuda_paths_windows(command: &mut tokio::process::Command) -> bool {+ use std::collections::HashSet;+ use std::path::Path;++ let mut cuda_paths = HashSet::new();++ // Check CUDA_PATH env var+ if let Ok(cuda_path) = std::env::var("CUDA_PATH") {+ let bin_path = format!(r"{}\bin", cuda_path);+ if Path::new(&bin_path).exists() {+ cuda_paths.insert(bin_path);+ }+ }++ // Check versioned CUDA_PATH_Vxx_x env vars+ for (key, value) in std::env::vars() {+ if key.starts_with("CUDA_PATH_V") {+ let bin_path = format!(r"{}\bin", value);+ if Path::new(&bin_path).exists() {+ cuda_paths.insert(bin_path);+ }+ }+ }++ // Check common installation directories+ let program_files =+ std::env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".to_string());+ let cuda_toolkit_base = format!(r"{}\NVIDIA GPU Computing Toolkit\CUDA", program_files);++ if let Ok(entries) = std::fs::read_dir(&cuda_toolkit_base) {+ for entry in entries.flatten() {+ if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {+ let bin_path = entry.path().join("bin");+ if bin_path.exists() {+ cuda_paths.insert(bin_path.to_string_lossy().to_string());+ }+ }+ }+ }++ // Update PATH if we found CUDA+ if !cuda_paths.is_empty() {+ let mut paths: Vec<_> = cuda_paths.into_iter().collect();+ paths.sort();++ let current_path = std::env::var("PATH").unwrap_or_default();+ let current_path = current_path.trim_end_matches(';');+ let new_path = format!("{};{}", paths.join(";"), current_path);++ command.env("PATH", new_path);++ #[cfg(feature = "logging")]+ log::info!("Added CUDA paths to PATH: {}", paths.join(", "));++ true+ } else {+ #[cfg(feature = "logging")]+ log::debug!("CUDA not found on Windows system");+ false+ }+}++#[cfg(target_os = "linux")]+pub fn add_cuda_paths_linux(command: &mut tokio::process::Command) -> bool {+ use std::collections::HashSet;+ use std::path::Path;++ let mut cuda_lib_paths = HashSet::new();+ let mut cuda_bin_paths = HashSet::new();++ // Check CUDA_HOME or CUDA_PATH environment variables+ if let Ok(cuda_path) = std::env::var("CUDA_HOME").or_else(|_| std::env::var("CUDA_PATH")) {+ let lib64_path = format!("{}/lib64", cuda_path);+ let lib_path = format!("{}/lib", cuda_path);+ let bin_path = format!("{}/bin", cuda_path);++ if Path::new(&lib64_path).exists() {+ cuda_lib_paths.insert(lib64_path);+ }+ if Path::new(&lib_path).exists() {+ cuda_lib_paths.insert(lib_path);+ }+ if Path::new(&bin_path).exists() {+ cuda_bin_paths.insert(bin_path);+ }+ }++ // Common CUDA directories+ let common_paths = [+ "/usr/local/cuda/lib64",+ "/usr/local/cuda/lib",+ "/usr/lib/cuda/lib64",+ "/usr/lib/cuda/lib",+ "/opt/cuda/lib64",+ "/opt/cuda/lib",+ "/usr/lib/x86_64-linux-gnu",+ "/usr/lib/x86_64-linux-gnu/nvidia",+ ];++ for path in &common_paths {+ if Path::new(path).exists() {+ cuda_lib_paths.insert(path.to_string());}}++ // Version-specific installs like /usr/local/cuda-12.2+ if let Ok(entries) = std::fs::read_dir("/usr/local") {+ for entry in entries.flatten() {+ if let Some(name) = entry.file_name().to_str() {+ if name.starts_with("cuda-") {+ let base = entry.path();+ for sub in ["lib64", "lib", "bin"] {+ let sub_path = base.join(sub);+ if sub_path.exists() {+ let s = sub_path.to_string_lossy().to_string();+ if sub == "bin" {+ cuda_bin_paths.insert(s);+ } else {+ cuda_lib_paths.insert(s);+ }+ }+ }+ }+ }+ }+ }++ // Merge and inject paths+ let mut modified = false;++ if !cuda_lib_paths.is_empty() {+ let mut libs: Vec<_> = cuda_lib_paths.into_iter().collect();+ libs.sort();++ let current_ld_path = std::env::var("LD_LIBRARY_PATH").unwrap_or_default();+ let current_ld_path = current_ld_path.trim_end_matches(':');+ let new_ld_path = if current_ld_path.is_empty() {+ libs.join(":")+ } else {+ format!("{}:{}", libs.join(":"), current_ld_path)+ };++ command.env("LD_LIBRARY_PATH", new_ld_path);+ modified = true;++ #[cfg(feature = "logging")]+ log::info!("Added CUDA libs to LD_LIBRARY_PATH: {}", libs.join(", "));+ }++ if !cuda_bin_paths.is_empty() {+ let mut bins: Vec<_> = cuda_bin_paths.into_iter().collect();+ bins.sort();++ let current_path = std::env::var("PATH").unwrap_or_default();+ let current_path = current_path.trim_end_matches(':');+ let new_path = if current_path.is_empty() {+ bins.join(":")+ } else {+ format!("{}:{}", bins.join(":"), current_path)+ };++ command.env("PATH", new_path);+ modified = true;++ #[cfg(feature = "logging")]+ log::info!("Added CUDA bins to PATH: {}", bins.join(", "));+ }++ if !modified {+ #[cfg(feature = "logging")]+ log::debug!("CUDA not found on Linux system");+ }++ modified}/// Setup Windows-specific process creation flags