Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): detect ROCm in versioned /opt/rocm-* dirs
Akarshan Biswas4dd01d290f37
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rsindex 6e5574cfd..ff3080486 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs@@ -970,7 +970,17 @@ fn verify_backend_dependencies(let _ = exe_path;- let analysis = crate::deps_analyzer::analyze_out_of_process(bin_dir, &paths);+ // HIP/ROCm runtime libs (rocblas/hipblas/amdhip) live outside the backend+ // dir in versioned roots like /opt/rocm-7.2.0/lib; add them so the scan+ // doesn't false-flag them as missing.+ let mut lib_dirs: Vec<PathBuf> = vec![bin_dir.to_path_buf()];+ if gpu_backend_keyword(backend) == Some("hip") {+ for p in jan_utils::find_rocm_paths().lib_paths {+ lib_dirs.push(PathBuf::from(p));+ }+ }++ let analysis = crate::deps_analyzer::analyze_out_of_process(&lib_dirs, &paths);let resolved: std::collections::HashSet<String> = analysis.resolved.into_iter().collect();for name in analysis.missing {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rsindex 324d0b035..39d1b2994 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs@@ -5,7 +5,7 @@use serde::{Deserialize, Serialize};#[cfg(not(target_os = "macos"))]use std::collections::HashSet;-use std::path::{Path, PathBuf};+use std::path::PathBuf;#[cfg(not(target_os = "macos"))]use std::process::{Command, Stdio};@@ -28,17 +28,19 @@ pub fn run_deps_analyzer_if_requested() {return;}- let lib_dir = match args.next() {- Some(d) => PathBuf::from(d),+ // First arg is the platform-joined list of library search dirs (the+ // backend's own dir plus any GPU runtime dirs, e.g. ROCm under /opt).+ let lib_dirs: Vec<PathBuf> = match args.next() {+ Some(d) => std::env::split_paths(&d).collect(),None => {- eprintln!("{}: missing <lib_dir> argument", ANALYZE_FLAG);+ eprintln!("{}: missing <lib_dirs> argument", ANALYZE_FLAG);std::process::exit(2);}};let targets: Vec<PathBuf> = args.map(PathBuf::from).collect();let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- analyze(&lib_dir, &targets)+ analyze(&lib_dirs, &targets)}));match result {@@ -65,9 +67,11 @@ pub fn run_deps_analyzer_if_requested() {}#[cfg(not(target_os = "macos"))]-fn analyze(lib_dir: &Path, targets: &[PathBuf]) -> AnalyzeOutput {- let analyzer =- lddtree::DependencyAnalyzer::default().add_library_path(lib_dir.to_path_buf());+fn analyze(lib_dirs: &[PathBuf], targets: &[PathBuf]) -> AnalyzeOutput {+ let mut analyzer = lddtree::DependencyAnalyzer::default();+ for dir in lib_dirs {+ analyzer = analyzer.add_library_path(dir.to_path_buf());+ }let mut missing: HashSet<String> = HashSet::new();let mut resolved: HashSet<String> = HashSet::new();@@ -103,12 +107,12 @@ pub(crate) fn is_virtual_windows_dll(name: &str) -> bool {// macOS resolves dynamic libraries via dyld at load time; lddtree's Mach-O// handling is unreliable and has crashed in the field, so skip the analyzer.#[cfg(target_os = "macos")]-pub fn analyze_out_of_process(_lib_dir: &Path, _targets: &[PathBuf]) -> AnalyzeOutput {+pub fn analyze_out_of_process(_lib_dirs: &[PathBuf], _targets: &[PathBuf]) -> AnalyzeOutput {AnalyzeOutput::default()}#[cfg(not(target_os = "macos"))]-pub fn analyze_out_of_process(lib_dir: &Path, targets: &[PathBuf]) -> AnalyzeOutput {+pub fn analyze_out_of_process(lib_dirs: &[PathBuf], targets: &[PathBuf]) -> AnalyzeOutput {let exe = match std::env::current_exe() {Ok(p) => p,Err(e) => {@@ -117,8 +121,16 @@ pub fn analyze_out_of_process(lib_dir: &Path, targets: &[PathBuf]) -> AnalyzeOut}};+ let joined = match std::env::join_paths(lib_dirs) {+ Ok(s) => s,+ Err(e) => {+ log::warn!("deps_analyzer: failed to join lib dirs: {}", e);+ return AnalyzeOutput::default();+ }+ };+let mut cmd = Command::new(&exe);- cmd.arg(ANALYZE_FLAG).arg(lib_dir);+ cmd.arg(ANALYZE_FLAG).arg(joined);for t in targets {cmd.arg(t);}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rsindex 8465933c3..5812c4c7c 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs@@ -7,7 +7,10 @@ use tokio::time::timeout;use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};use crate::path::validate_binary_path;-use jan_utils::{binary_requires_cuda, find_cuda_paths, setup_library_path, setup_windows_process_flags};+use jan_utils::{+ binary_requires_cuda, binary_requires_rocm, find_cuda_paths, find_rocm_paths,+ setup_library_path, setup_windows_process_flags,+};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct DeviceInfo {@@ -40,7 +43,13 @@ pub async fn get_devices_from_backend("llama.cpp backend appears to require CUDA, but CUDA not found. Process may fail to start. Please install cuda runtime and try again!");}- setup_library_path(bin_path.parent(), &cuda, &mut command);+ let rocm = find_rocm_paths();+ if rocm.lib_paths.is_empty() && rocm.bin_paths.is_empty() && binary_requires_rocm(&bin_path) {+ log::warn!(+ "llama.cpp backend appears to require ROCm/HIP, but ROCm not found. Process may fail to start. Please install the ROCm runtime and try again!"+ );+ }+ setup_library_path(bin_path.parent(), &cuda.merged(rocm), &mut command);// Execute the command and wait for completionlet output = timeout(Duration::from_secs(30), command.output())diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rsindex fc9442c8f..95bc14733 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs@@ -69,7 +69,10 @@ fn is_backend_error_line(line_lower: &str) -> bool {}use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};-use jan_utils::{binary_requires_cuda, find_cuda_paths, setup_library_path, setup_windows_process_flags};+use jan_utils::{+ binary_requires_cuda, binary_requires_rocm, find_cuda_paths, find_rocm_paths,+ setup_library_path, setup_windows_process_flags,+};/// A handle to a running router-mode `llama-server` process.pub struct RouterHandle {@@ -160,7 +163,17 @@ pub async fn start_router(Process may fail to start.");}- setup_library_path(backend_exe.parent(), &cuda, &mut command);+ let rocm = find_rocm_paths();+ if rocm.lib_paths.is_empty()+ && rocm.bin_paths.is_empty()+ && binary_requires_rocm(&backend_exe)+ {+ log::warn!(+ "llama.cpp router backend appears to require ROCm/HIP, but ROCm not found. \+ Process may fail to start."+ );+ }+ setup_library_path(backend_exe.parent(), &cuda.merged(rocm), &mut command);let mut child = command.spawn().map_err(ServerError::Io)?;diff --git a/src-tauri/utils/src/system.rs b/src-tauri/utils/src/system.rsindex 016ecd8cb..33af47d81 100644--- a/src-tauri/utils/src/system.rs+++ b/src-tauri/utils/src/system.rs@@ -51,6 +51,24 @@ pub struct CudaPaths {pub bin_paths: Vec<String>,}+impl CudaPaths {+ /// Folds another set of GPU runtime paths in, de-duplicating. Used to merge+ /// CUDA + ROCm discovery into one `setup_library_path` call.+ pub fn merged(mut self, other: CudaPaths) -> CudaPaths {+ for p in other.lib_paths {+ if !self.lib_paths.contains(&p) {+ self.lib_paths.push(p);+ }+ }+ for p in other.bin_paths {+ if !self.bin_paths.contains(&p) {+ self.bin_paths.push(p);+ }+ }+ self+ }+}+/// Merges binary lib dir + CUDA paths into a single `command.env()` call per variable.pub fn setup_library_path(library_path: Option<&Path>,@@ -203,6 +221,139 @@ pub fn find_cuda_paths() -> CudaPaths {}}+/// Locates ROCm/HIP runtime directories. Mirrors `find_cuda_paths`: ROCm ships+/// in versioned roots (e.g. `/opt/rocm-7.2.0/lib`) that aren't on the default+/// loader path, so they must be discovered and added explicitly.+pub fn find_rocm_paths() -> CudaPaths {+ #[cfg(target_os = "linux")]+ return find_rocm_paths_linux();++ #[cfg(target_os = "windows")]+ return find_rocm_paths_windows();++ #[cfg(not(any(target_os = "windows", target_os = "linux")))]+ CudaPaths::default()+}++#[cfg(target_os = "linux")]+fn add_rocm_root(+ root: &std::path::Path,+ lib_paths: &mut std::collections::HashSet<String>,+ bin_paths: &mut std::collections::HashSet<String>,+) {+ for sub in ["lib", "lib64"] {+ let p = root.join(sub);+ if p.exists() {+ lib_paths.insert(p.to_string_lossy().to_string());+ }+ }+ let bin = root.join("bin");+ if bin.exists() {+ bin_paths.insert(bin.to_string_lossy().to_string());+ }+}++#[cfg(target_os = "linux")]+fn find_rocm_paths_linux() -> CudaPaths {+ use std::collections::HashSet;+ use std::path::Path;++ let mut lib_paths: HashSet<String> = HashSet::new();+ let mut bin_paths: HashSet<String> = HashSet::new();++ for var in ["ROCM_PATH", "ROCM_HOME", "HIP_PATH"] {+ if let Ok(root) = std::env::var(var) {+ add_rocm_root(Path::new(&root), &mut lib_paths, &mut bin_paths);+ }+ }++ // Canonical unversioned symlink.+ add_rocm_root(Path::new("/opt/rocm"), &mut lib_paths, &mut bin_paths);++ // Versioned installs: /opt/rocm-7.2.0, /opt/rocm-6.4.1, ...+ if let Ok(entries) = std::fs::read_dir("/opt") {+ for entry in entries.flatten() {+ if let Some(name) = entry.file_name().to_str() {+ if name.starts_with("rocm-") {+ add_rocm_root(&entry.path(), &mut lib_paths, &mut bin_paths);+ }+ }+ }+ }++ let mut libs: Vec<_> = lib_paths.into_iter().collect();+ libs.sort();+ let mut bins: Vec<_> = bin_paths.into_iter().collect();+ bins.sort();++ #[cfg(feature = "logging")]+ if libs.is_empty() && bins.is_empty() {+ log::debug!("ROCm not found on Linux system");+ } else if !libs.is_empty() {+ log::info!("Found ROCm lib paths: {}", libs.join(", "));+ }++ CudaPaths {+ lib_paths: libs,+ bin_paths: bins,+ }+}++#[cfg(target_os = "windows")]+fn find_rocm_paths_windows() -> CudaPaths {+ use std::collections::HashSet;+ use std::path::Path;++ let mut bin_paths = HashSet::new();++ if let Ok(hip_path) = std::env::var("HIP_PATH").or_else(|_| std::env::var("ROCM_PATH")) {+ let bin = format!(r"{}\bin", hip_path);+ if Path::new(&bin).exists() {+ bin_paths.insert(bin);+ }+ }++ let program_files =+ std::env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".to_string());+ let rocm_base = format!(r"{}\AMD\ROCm", program_files);+ if let Ok(entries) = std::fs::read_dir(&rocm_base) {+ for entry in entries.flatten() {+ if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {+ let bin = entry.path().join("bin");+ if bin.exists() {+ bin_paths.insert(bin.to_string_lossy().to_string());+ }+ }+ }+ }++ let mut bins: Vec<_> = bin_paths.into_iter().collect();+ bins.sort();+ CudaPaths {+ lib_paths: Vec::new(),+ bin_paths: bins,+ }+}++/// True when the binary links the HIP/ROCm runtime (libamdhip64 / rocblas /+/// hipblas). Used to warn when a HIP backend is run without ROCm present.+pub fn binary_requires_rocm(_bin_path: &Path) -> bool {+ #[cfg(target_os = "linux")]+ {+ 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("libamdhip64")+ || stdout.contains("librocblas")+ || stdout.contains("libhipblas");+ }+ }+ false+ }+ #[cfg(not(target_os = "linux"))]+ false+}+/// Backward-compat wrapper. Prefer `find_cuda_paths()` + `setup_library_path()`.pub fn add_cuda_paths(command: &mut tokio::process::Command) -> bool {let cuda = find_cuda_paths();@@ -564,6 +715,34 @@ mod tests {}}+ #[test]+ fn find_rocm_paths_returns_existing_dirs() {+ let rp = find_rocm_paths();+ for p in rp.lib_paths.iter().chain(rp.bin_paths.iter()) {+ assert!(Path::new(p).exists(), "Returned ROCm path should exist: {}", p);+ }+ }++ #[test]+ fn binary_requires_rocm_returns_false_for_nonexistent_file() {+ assert!(!binary_requires_rocm(Path::new("/nonexistent/binary")));+ }++ #[test]+ fn merged_dedups_and_unions_paths() {+ let a = CudaPaths {+ lib_paths: vec!["/x".into(), "/y".into()],+ bin_paths: vec!["/b".into()],+ };+ let b = CudaPaths {+ lib_paths: vec!["/y".into(), "/z".into()],+ bin_paths: vec!["/b".into(), "/c".into()],+ };+ let m = a.merged(b);+ assert_eq!(m.lib_paths, vec!["/x", "/y", "/z"]);+ assert_eq!(m.bin_paths, vec!["/b", "/c"]);+ }+#[tokio::test]async fn add_cuda_paths_compat_wrapper_does_not_panic() {let mut cmd = new_shell_command();