Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(llamacpp): log the NVIDIA driver at engine start and explain a driver too old for the engine

thinhlpg49772b8c159a
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 09a3b48d7..84e7cac66 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -252,6 +252,16 @@ mod engine {
println!("cargo:rerun-if-env-changed=JAN_ENGINE_BUILD_LOG");
println!("cargo:rerun-if-env-changed=JAN_ENGINE_BUILD_DIR");
+ // The worker reports this in its handshake so the app can set it against
+ // the NVIDIA driver (#9189). Read on the prebuilt path too: the prebuilt
+ // key includes the full nvcc version, so a cache hit is built with the
+ // toolkit that is on this host.
+ if feature_enabled("engine-cuda") {
+ if let Some((_, v)) = nvcc_version() {
+ println!("cargo:rustc-env=JAN_ENGINE_CUDA_TOOLKIT={}.{}", v.0, v.1);
+ }
+ }
+
// Headers are always needed: the shim is our code and is compiled
// here even when the archives come prebuilt, so it cannot drift from
// the crate.
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
index c772e9fc0..e1b65a946 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
@@ -202,6 +202,9 @@ async fn main() {
"port": server.port,
"pid": std::process::id(),
"models": models,
+ // Set by build.rs for a CUDA engine; null otherwise. The app sets it
+ // against the NVIDIA driver to explain a driver that is too old.
+ "cuda_toolkit": option_env!("JAN_ENGINE_CUDA_TOOLKIT"),
})
);
// stdout is a pipe to the supervisor, so it is block-buffered.
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
index 16285b486..169e9d076 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
@@ -7,7 +7,9 @@ use std::sync::Arc;
use rand::Rng;
use serde::{Deserialize, Serialize};
use tauri::{Manager, State};
+use tauri_plugin_hardware::vendor::nvidia::{nvidia_driver, CudaVersion};
+use super::driver;
use super::worker::{self, WorkerHandle};
use crate::state::LlamacppState;
@@ -127,16 +129,42 @@ fn worker_missing_message(tried: &[PathBuf]) -> String {
/// Forwards a worker fault to the frontend, which turns it into the OOM or
/// backend-error dialog. A mid-generation `GGML_ASSERT` kills the worker
/// outright, so its log line is the only account of what happened.
-fn fault_emitter<R: tauri::Runtime>(app_handle: tauri::AppHandle<R>) -> worker::FaultCallback {
+///
+/// A driver too old for the engine's CUDA code is told apart from a generic
+/// backend crash, and the banner (which shows this text verbatim) says to
+/// update the driver instead of leaving the user with a bare ggml abort.
+fn fault_emitter<R: tauri::Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ toolkit: Arc<std::sync::OnceLock<CudaVersion>>,
+) -> worker::FaultCallback {
use tauri::Emitter;
Arc::new(move |fault: worker::RuntimeFault, line: String| {
log::error!("jan-llama-worker fault ({fault:?}): {line}");
- if let Err(e) = app_handle.emit(fault.event_name(), line) {
+ let payload =
+ driver::fault_payload(&line, nvidia_driver().as_ref(), toolkit.get().copied());
+ if let Err(e) = app_handle.emit(fault.event_name(), payload) {
log::warn!("emit {} failed: {e}", fault.event_name());
}
})
}
+/// Writes the NVIDIA driver and CUDA versions to `app.log` next to the engine's
+/// own toolkit, and warns when the driver is older than the engine. Without
+/// this a CUDA failure on an old driver cannot be told from any other (#9185).
+async fn log_nvidia_driver(toolkit: Option<CudaVersion>) {
+ // NVML loads a shared library and may take a moment on first use.
+ let Ok(Some(driver)) = tokio::task::spawn_blocking(nvidia_driver).await else {
+ return;
+ };
+ log::info!("{}", driver::startup_line(&driver, toolkit));
+ if driver::driver_older_than_engine(&driver, toolkit) {
+ log::warn!(
+ "{} GPUs the engine has no native code for will fail to load.",
+ driver::actionable_message(&driver, toolkit)
+ );
+ }
+}
+
/// Starts the worker. `slot_cache_mib` is the ceiling on the per-thread KV
/// cache directory; 0 turns cross-session KV persistence off, which is a
/// user-facing setting because a single saved conversation is hundreds of MiB.
@@ -157,6 +185,9 @@ pub async fn start_engine<R: tauri::Runtime>(
let exe = resolve_worker_exe(&app_handle)?;
let api_key = generate_worker_key();
+ // Filled from the handshake, after the worker is up; a fault before then
+ // is worded without it.
+ let toolkit = Arc::new(std::sync::OnceLock::new());
let handle = worker::spawn(
&exe,
&PathBuf::from(preset_path),
@@ -165,10 +196,14 @@ pub async fn start_engine<R: tauri::Runtime>(
models_max,
slot_cache_mib,
envs,
- Some(fault_emitter(app_handle.clone())),
+ Some(fault_emitter(app_handle.clone(), toolkit.clone())),
)
.await
.map_err(|e| e.to_string())?;
+ if let Some(v) = handle.cuda_toolkit {
+ let _ = toolkit.set(v);
+ }
+ log_nvidia_driver(handle.cuda_toolkit).await;
let info = EngineInfo::from(&handle);
// Subscribed here rather than lazily: an eviction can happen on the very
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/driver.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/driver.rs
new file mode 100644
index 000000000..fcb7af8da
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/driver.rs
@@ -0,0 +1,187 @@
+//! What the NVIDIA driver can run, set against what the engine was built with.
+//!
+//! The engine's CUDA toolkit decides how new a driver it needs. A GPU with
+//! native code in the engine runs on an older driver, but one that is only
+//! covered by PTX (sm_80 and sm_90, and any GPU newer than the engine) is
+//! compiled by the driver on first use, and a driver older than the toolkit that
+//! wrote the PTX refuses it. The worker then aborts with no word on why, so the
+//! versions are logged at start and named in the error when it happens (#9185).
+
+use tauri_plugin_hardware::vendor::nvidia::{CudaVersion, NvidiaDriver};
+
+/// The oldest NVIDIA driver release branch that runs a given toolkit's PTX.
+/// Only the pairs that have been confirmed are listed; for any other toolkit
+/// the advice just says to update.
+fn minimum_branch(toolkit: CudaVersion) -> Option<u32> {
+ match (toolkit.major, toolkit.minor) {
+ (13, 2) => Some(595),
+ _ => None,
+ }
+}
+
+/// The driver is older than the engine's toolkit, so PTX-only GPUs will not run.
+pub fn driver_older_than_engine(driver: &NvidiaDriver, toolkit: Option<CudaVersion>) -> bool {
+ matches!((driver.cuda, toolkit), (Some(supported), Some(built)) if supported < built)
+}
+
+/// One line for `app.log` at engine start, so a later failure can be read
+/// against the versions it ran with.
+pub fn startup_line(driver: &NvidiaDriver, toolkit: Option<CudaVersion>) -> String {
+ format!(
+ "NVIDIA driver {} supports CUDA {}; engine built with CUDA {}",
+ driver.version,
+ driver.cuda.map_or("unknown".into(), |v| v.to_string()),
+ toolkit.map_or("unknown".into(), |v| v.to_string()),
+ )
+}
+
+/// What to tell the user when the engine reports the driver cannot run its
+/// code. Leads with the action, then the versions that explain it.
+pub fn actionable_message(driver: &NvidiaDriver, toolkit: Option<CudaVersion>) -> String {
+ let update = match toolkit.and_then(minimum_branch) {
+ Some(branch) => format!("Update your NVIDIA driver to R{branch} or newer."),
+ None => "Update your NVIDIA driver to the latest version.".to_string(),
+ };
+ let cuda = driver
+ .cuda
+ .map_or(String::new(), |v| format!(" (supports CUDA {v})"));
+ let built = toolkit.map_or(String::new(), |v| format!(", built with CUDA {v}"));
+ format!(
+ "{update} The installed driver {}{cuda} is too old for this engine{built}.",
+ driver.version
+ )
+}
+
+/// The text the backend-error banner shows for a worker fault line. A line that
+/// says the driver cannot run the engine's code gets the update advice ahead of
+/// ggml's own words; anything else, or no NVIDIA driver to name, is passed through.
+pub fn fault_payload(
+ line: &str,
+ driver: Option<&NvidiaDriver>,
+ toolkit: Option<CudaVersion>,
+) -> String {
+ match driver {
+ Some(driver) if crate::error::is_driver_too_old(&line.to_lowercase()) => {
+ format!(
+ "{} Engine output: {line}",
+ actionable_message(driver, toolkit)
+ )
+ }
+ _ => line.to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn driver(version: &str, cuda: Option<(u32, u32)>) -> NvidiaDriver {
+ NvidiaDriver {
+ version: version.into(),
+ cuda: cuda.map(|(major, minor)| CudaVersion { major, minor }),
+ }
+ }
+
+ const CUDA_13_2: Option<CudaVersion> = Some(CudaVersion {
+ major: 13,
+ minor: 2,
+ });
+
+ #[test]
+ fn a_driver_supporting_older_cuda_than_the_engine_is_too_old() {
+ assert!(driver_older_than_engine(
+ &driver("580.88", Some((13, 0))),
+ CUDA_13_2
+ ));
+ assert!(!driver_older_than_engine(
+ &driver("595.97", Some((13, 2))),
+ CUDA_13_2
+ ));
+ assert!(!driver_older_than_engine(
+ &driver("600.1", Some((13, 3))),
+ CUDA_13_2
+ ));
+ }
+
+ // With either side unknown there is nothing to compare, and guessing would
+ // tell a user with a working driver to update it.
+ #[test]
+ fn an_unknown_version_is_never_called_too_old() {
+ assert!(!driver_older_than_engine(
+ &driver("580.88", None),
+ CUDA_13_2
+ ));
+ assert!(!driver_older_than_engine(
+ &driver("580.88", Some((13, 0))),
+ None
+ ));
+ }
+
+ #[test]
+ fn the_startup_line_names_the_driver_and_both_cuda_versions() {
+ assert_eq!(
+ startup_line(&driver("580.88", Some((13, 0))), CUDA_13_2),
+ "NVIDIA driver 580.88 supports CUDA 13.0; engine built with CUDA 13.2"
+ );
+ assert_eq!(
+ startup_line(&driver("580.88", None), None),
+ "NVIDIA driver 580.88 supports CUDA unknown; engine built with CUDA unknown"
+ );
+ }
+
+ #[test]
+ fn the_message_asks_for_r595_when_the_engine_is_cuda_13_2() {
+ let msg = actionable_message(&driver("580.88", Some((13, 0))), CUDA_13_2);
+ assert!(
+ msg.starts_with("Update your NVIDIA driver to R595 or newer."),
+ "{msg}"
+ );
+ assert!(msg.contains("580.88"), "{msg}");
+ assert!(msg.contains("supports CUDA 13.0"), "{msg}");
+ assert!(msg.contains("built with CUDA 13.2"), "{msg}");
+ }
+
+ // A threshold is only stated where one is known; inventing one for another
+ // toolkit would send users to a driver that may still be too old.
+ #[test]
+ fn the_message_does_not_invent_a_driver_floor() {
+ for toolkit in [
+ Some(CudaVersion {
+ major: 12,
+ minor: 9,
+ }),
+ None,
+ ] {
+ let msg = actionable_message(&driver("470.1", None), toolkit);
+ assert!(
+ msg.starts_with("Update your NVIDIA driver to the latest version."),
+ "{msg}"
+ );
+ assert!(!msg.contains(" R"), "{msg}");
+ }
+ }
+
+ const PTX_LINE: &str =
+ "CUDA error: the provided PTX was compiled with an unsupported toolchain.";
+
+ #[test]
+ fn a_ptx_toolchain_fault_gets_the_update_advice_ahead_of_ggmls_words() {
+ let payload = fault_payload(PTX_LINE, Some(&driver("580.88", Some((13, 0)))), CUDA_13_2);
+ assert!(
+ payload.starts_with("Update your NVIDIA driver to R595 or newer."),
+ "{payload}"
+ );
+ assert!(
+ payload.ends_with(&format!("Engine output: {PTX_LINE}")),
+ "{payload}"
+ );
+ }
+
+ #[test]
+ fn other_faults_and_a_missing_driver_pass_through_untouched() {
+ let nvidia = driver("580.88", Some((13, 0)));
+ let oom = "CUDA error: out of memory";
+ assert_eq!(fault_payload(oom, Some(&nvidia), CUDA_13_2), oom);
+ assert_eq!(fault_payload(PTX_LINE, None, CUDA_13_2), PTX_LINE);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
index 3b218fe40..f0b54093f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
@@ -15,6 +15,7 @@
use std::fmt;
pub mod commands;
+pub mod driver;
pub mod events;
pub mod http;
pub mod preset;
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
index b4d44721d..ad4963c85 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
+use tauri_plugin_hardware::vendor::nvidia::CudaVersion;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
@@ -25,6 +26,9 @@ pub struct Handshake {
pub port: u16,
pub pid: u32,
pub models: Vec<String>,
+ /// The CUDA toolkit the engine was built with, which decides how new an
+ /// NVIDIA driver it needs.
+ pub cuda_toolkit: Option<CudaVersion>,
}
#[derive(Debug, PartialEq, Eq)]
@@ -194,7 +198,19 @@ pub fn parse_handshake(line: &str) -> Result<Handshake, WorkerError> {
.collect()
})
.unwrap_or_default();
- Ok(Handshake { port, pid, models })
+ // Absent for a worker without CUDA, or one built where nvcc could not be
+ // read. Unreadable is treated the same: the handshake is not the place to
+ // fail over a diagnostic.
+ let cuda_toolkit = v
+ .get("cuda_toolkit")
+ .and_then(serde_json::Value::as_str)
+ .and_then(CudaVersion::parse);
+ Ok(Handshake {
+ port,
+ pid,
+ models,
+ cuda_toolkit,
+ })
}
impl std::fmt::Debug for WorkerHandle {
@@ -279,6 +295,8 @@ pub struct WorkerHandle {
pub pid: u32,
pub api_key: String,
pub models: Vec<String>,
+ /// The CUDA toolkit the engine was built with, when it reported one.
+ pub cuda_toolkit: Option<CudaVersion>,
child: Child,
/// Declared after `child` so it is dropped after it: the graceful stop must
/// get its turn before closing the job would kill the worker outright.
@@ -479,6 +497,7 @@ pub async fn spawn(
pid: hs.pid,
api_key: api_key.to_string(),
models: hs.models,
+ cuda_toolkit: hs.cuda_toolkit,
child,
#[cfg(windows)]
_job: job,
@@ -629,13 +648,17 @@ mod tests {
#[test]
fn parse_handshake_reads_the_worker_line() {
- let hs = parse_handshake(r#"{"port":39271,"pid":1234,"models":["a","b"]}"#).unwrap();
+ let hs = parse_handshake(
+ r#"{"port":39271,"pid":1234,"models":["a","b"],"cuda_toolkit":"13.2"}"#,
+ )
+ .unwrap();
assert_eq!(
hs,
Handshake {
port: 39271,
pid: 1234,
models: vec!["a".into(), "b".into()],
+ cuda_toolkit: Some(CudaVersion { major: 13, minor: 2 }),
}
);
}
@@ -646,6 +669,22 @@ mod tests {
assert_eq!(hs.port, 8080);
assert_eq!(hs.pid, 0);
assert!(hs.models.is_empty());
+ assert_eq!(hs.cuda_toolkit, None);
+ }
+
+ // A worker built without CUDA, or by a build that could not read nvcc,
+ // reports null; an unreadable value must not fail the whole handshake.
+ #[test]
+ fn parse_handshake_treats_an_absent_or_unreadable_toolkit_as_unknown() {
+ for line in [
+ r#"{"port":8080,"cuda_toolkit":null}"#,
+ r#"{"port":8080,"cuda_toolkit":"thirteen"}"#,
+ r#"{"port":8080,"cuda_toolkit":13}"#,
+ ] {
+ let hs = parse_handshake(line).unwrap();
+ assert_eq!(hs.port, 8080, "{line}");
+ assert_eq!(hs.cuda_toolkit, None, "{line}");
+ }
}
#[test]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
index 8675d038a..e84e2f813 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
@@ -120,12 +120,18 @@ const MISSING_LIBRARY_MARKERS: [&str; 5] = [
"image not found",
];
-const DRIVER_TOO_OLD_MARKERS: [&str; 5] = [
+const DRIVER_TOO_OLD_MARKERS: [&str; 8] = [
"driver version is insufficient",
"cudaerrorinsufficientdriver",
"error_incompatible_driver",
"unsupported display driver",
"forward compatibility was attempted on non supported",
+ // A GPU with no native code in the engine is compiled from PTX by the
+ // driver on first use, and a driver older than the toolkit that wrote the
+ // PTX refuses it (#9185).
+ "compiled with an unsupported toolchain",
+ "cuda_error_unsupported_ptx_version",
+ "cudaerrorunsupportedptxversion",
];
fn is_missing_library(lower: &str) -> bool {
@@ -134,7 +140,9 @@ fn is_missing_library(lower: &str) -> bool {
.any(|m| lower.contains(m))
}
-fn is_driver_too_old(lower: &str) -> bool {
+/// True for a lowercased engine line that says the NVIDIA/Vulkan driver is too
+/// old for the engine.
+pub fn is_driver_too_old(lower: &str) -> bool {
DRIVER_TOO_OLD_MARKERS
.iter()
.any(|m| lower.contains(m))
@@ -361,6 +369,10 @@ mod tests {
"ggml_vulkan: vkCreateInstance failed: ERROR_INCOMPATIBLE_DRIVER",
"forward compatibility was attempted on non supported HW",
"system has unsupported display driver / cuda driver combination",
+ // What ggml prints when the driver cannot compile the engine's PTX.
+ "CUDA error: the provided PTX was compiled with an unsupported toolchain.",
+ "cuda_error_unsupported_ptx_version",
+ "cudaErrorUnsupportedPtxVersion",
] {
let err = classify(stderr);
assert!(matches!(err.code, ErrorCode::GpuDriverTooOld), "{stderr} -> {err:?}");