Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(engine): die Schichtzahl wird am Grafikspeicher gemessen statt geraten

purpleccdc2d14c11f
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 35fae92c..d9f3aa2f 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -184,16 +184,199 @@ pub(crate) fn model_can_see_images(model_path: &str) -> bool {
existing_mmproj(model_path).is_some()
}
-/// Build the `llama-server` argv for a chat engine. `-ngl 999` offloads every
-/// layer to the GPU (Metal on mac); llama-server clamps to the real layer
-/// count, so an over-large value is the idiomatic "all layers" request.
-/// Default tuning yields exactly the legacy argv (pinned by regression test).
+// ── How much of a model a card can actually hold (3.0.0 list, bugs u and a) ──
+//
+// `-ngl 999` means "every layer on the graphics card". llama.cpp clamps it to
+// the model's real layer count, which is why it reads as the idiomatic way to
+// say "all of it", and on a roomy card it is. The two reports that opened this
+// are the other case:
+//
+// * Discord ticket-0009 (2026-09-07): a 12B model on an 8 GB RTX 4060. The
+// engine "start and exit again before it could serve on port 8127. It was
+// tried twice."
+// * GitHub 128 and two more Discord reports: a 3B Q4_K_M on a 2 GB card
+// answers with token soup.
+//
+// The app already knew how to ask this question and never asked it here: the
+// fit check lives in the model picker (`computeFit`, src/components/models/
+// ModelTiles.tsx), where it paints a coloured dot, and nothing of it ever
+// reached the engine arguments.
+//
+// NOT PROVEN ON THE REPORTERS' HARDWARE. There is no 2 GB and no 8 GB NVIDIA
+// card on the machine this was written on, so what is proven here is the
+// arithmetic, by the tests at the bottom of this file. What changes for a user
+// is narrower than "bug a is fixed": a card too small for the whole model is
+// no longer asked by default to take all of it, and the log now says what the
+// engine was told to do.
+
+/// One MiB, for the reserves below and the numbers in the log line.
+const MIB: u64 = 1024 * 1024;
+
+/// Graphics memory that is spoken for before a single weight is loaded: the
+/// driver's own context plus llama.cpp's compute buffers. A CUDA context alone
+/// runs to a few hundred MiB and the compute buffer adds a few hundred more at
+/// the default batch sizes, so 512 MiB is the round number above both.
+const VRAM_OVERHEAD_BYTES: u64 = 512 * MIB;
+
+/// KV cache per offloaded layer per 1024 tokens of context.
+///
+/// 4 MiB is the f16 figure for a modern grouped query model: K and V, 1024
+/// key and value dimensions, two bytes each, is 4 KiB per token per layer. A
+/// model with wider key and value heads needs more than this and will be given
+/// fewer layers than it could have held. That error costs speed. The opposite
+/// error costs the start, which is the failure this whole block exists to
+/// prevent.
+const KV_BYTES_PER_LAYER_PER_1K_CTX: u64 = 4 * MIB;
+
+/// The layer count assumed when the GGUF header does not carry one.
+///
+/// Deliberately LOW. The count only ever multiplies the fraction of the model
+/// that fits, so a guess BELOW the real block count can only ask for fewer
+/// layers than would have fit, never for more, and fewer layers is the
+/// direction in which a start survives. 16 is under the block count of every
+/// chat GGUF this app offers.
+const ASSUMED_BLOCK_COUNT: u32 = 16;
+
+/// What `-ngl` carries when every layer is wanted.
+const ALL_LAYERS: &str = "999";
+
+/// The numbers an offload decision is made from. Plain values, so the
+/// arithmetic can be checked without a graphics card in the machine.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct OffloadInputs {
+ /// The GGUF on disk. Its size is the honest proxy for what the weights
+ /// take in graphics memory at full offload, and the app already treats it
+ /// as one (`modelBytes` in `bundled_engine_status`, GH #85).
+ pub model_bytes: u64,
+ /// `<arch>.block_count` from the header, when it could be read.
+ pub block_count: Option<u32>,
+ /// Free graphics memory where a probe measured it, the card's total where
+ /// it could not, `None` where nothing measured a card at all.
+ pub vram_bytes: Option<u64>,
+ /// The context this start will ask for, which is what the KV cache is
+ /// sized from.
+ pub ctx: u32,
+}
+
+/// What the start should send as `-ngl`, and the sentence that explains it.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct OffloadPlan {
+ /// `None` means "ask for all layers": what this app has always sent, and
+ /// what a machine with room and a machine nothing could measure both keep
+ /// getting.
+ pub layers: Option<u32>,
+ /// One English clause for the log line, naming the numbers it decided on.
+ /// Without it the log would carry a layer count nobody could argue with.
+ pub why: String,
+}
+
+fn mib(bytes: u64) -> u64 {
+ bytes / MIB
+}
+
+/// Decide how many layers go on the card.
+///
+/// Three outcomes, and two of them are the old behaviour:
+///
+/// * Nothing measured a card: all layers, exactly as before, and the log
+/// says the probe came back empty.
+/// * The model and its cache fit with the reserve: all layers, exactly as
+/// before.
+/// * They do not fit: `floor(usable / per_layer)`, where `per_layer` is the
+/// file size divided by the block count plus that layer's share of the KV
+/// cache, and `usable` is the measured memory minus the driver reserve.
+///
+/// Pure. No file is read and no card is asked; the caller collects the inputs
+/// so this can be checked against hardware nobody here owns.
+pub(crate) fn plan_offload(input: &OffloadInputs) -> OffloadPlan {
+ let Some(vram) = input.vram_bytes else {
+ return OffloadPlan {
+ layers: None,
+ why: "no probe measured graphics memory on this machine, so every layer is requested exactly as before".to_string(),
+ };
+ };
+ // A header that answers zero is a header that answered nothing.
+ let read_from_header = input.block_count.filter(|b| *b > 0);
+ let blocks = read_from_header.unwrap_or(ASSUMED_BLOCK_COUNT);
+ // Round the context UP to whole thousands: a 6000 token context pays for
+ // six, because the error has to point at reserving too much.
+ let ctx_k = ((input.ctx.max(1) as u64) + 1023) / 1024;
+ let kv_per_layer = KV_BYTES_PER_LAYER_PER_1K_CTX * ctx_k;
+ let whole = input.model_bytes + kv_per_layer * blocks as u64 + VRAM_OVERHEAD_BYTES;
+ if whole <= vram {
+ return OffloadPlan {
+ layers: None,
+ why: format!(
+ "the model and its cache need about {} MiB and {} MiB are free, so every layer is requested",
+ mib(whole),
+ mib(vram)
+ ),
+ };
+ }
+ let usable = vram.saturating_sub(VRAM_OVERHEAD_BYTES);
+ let per_layer = input.model_bytes / blocks as u64 + kv_per_layer;
+ let layers = if per_layer == 0 {
+ 0
+ } else {
+ (usable / per_layer).min(blocks as u64) as u32
+ };
+ let counted = match read_from_header {
+ Some(b) => format!("{b} layers the GGUF header names"),
+ None => format!("{ASSUMED_BLOCK_COUNT} layers assumed, because the GGUF header carries no block count"),
+ };
+ OffloadPlan {
+ layers: Some(layers),
+ why: format!(
+ "the model and its cache need about {} MiB but only {} MiB are free, so {layers} of {counted} go on the card, at about {} MiB per layer and {} MiB held back for the driver and the compute buffers",
+ mib(whole),
+ mib(vram),
+ mib(per_layer),
+ mib(VRAM_OVERHEAD_BYTES)
+ ),
+ }
+}
+
+/// The `-ngl` value in a finished argv.
+///
+/// The retry reads the number back OUT of the arguments instead of working it
+/// out a second time, so the decision it makes can never disagree with what
+/// the first attempt was actually told.
+pub(crate) fn gpu_layers_in(args: &[String]) -> Option<u32> {
+ args.windows(2).find(|w| w[0] == "-ngl").and_then(|w| w[1].parse().ok())
+}
+
+/// The argv with the `-ngl <n>` pair removed, for the idempotence check.
+pub(crate) fn argv_without_gpu_layers(args: &[String]) -> Vec<String> {
+ let mut out = Vec::with_capacity(args.len());
+ let mut i = 0;
+ while i < args.len() {
+ if args[i] == "-ngl" && i + 1 < args.len() {
+ i += 2;
+ continue;
+ }
+ out.push(args[i].clone());
+ i += 1;
+ }
+ out
+}
+
+/// Build the `llama-server` argv for a chat engine.
+///
+/// `auto_ngl` is what `plan_offload` resolved the "auto" default to, and it is
+/// consulted ONLY when the user left GPU Layers on auto (`gpu_layers < 0`).
+/// `None` there means "ask for all layers" and produces the exact argv this
+/// app has always produced, which is what a machine nothing could measure and
+/// a machine with room both get. A typed number always wins over both: an
+/// expert who wrote 20 into Settings gets 20.
+///
+/// Default tuning with `auto_ngl` at `None` yields exactly the legacy argv
+/// (pinned by regression test).
///
/// `mmproj` turns the model multimodal. A text GGUF has no image tower, so
/// without the flag a vision model loads and answers, it just cannot see, which
/// is exactly the silent failure the Discover download avoids by fetching the
/// projector with the model.
-pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u16, slot_save_dir: Option<&str>, mmproj: Option<&str>) -> Vec<String> {
+pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u16, slot_save_dir: Option<&str>, mmproj: Option<&str>, auto_ngl: Option<u32>) -> Vec<String> {
let mut args: Vec<String> = vec![
"-m".into(),
model_path.into(),
@@ -205,7 +388,7 @@ pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u
effective_ctx(tuning).to_string(),
"-ngl".into(),
if tuning.gpu_layers < 0 {
- "999".into()
+ auto_ngl.map(|n| n.to_string()).unwrap_or_else(|| ALL_LAYERS.to_string())
} else {
tuning.gpu_layers.to_string()
},
@@ -1246,6 +1429,25 @@ pub(crate) fn with_note_on_top(message: &str, note: &str) -> String {
}
}
+/// What the second start attempt did differently, for the sentence the user
+/// reads. "It was tried twice" is a true but empty promise when both tries
+/// were the same experiment; naming the difference is what lets a reader tell
+/// a card that cannot hold the model from one that is broken.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) enum SecondAttempt {
+ /// One attempt only, or a retry that ran the same arguments (possibly on
+ /// another port).
+ SameOffload,
+ /// The retry dropped GPU offload and ran on the processor.
+ CpuOnly,
+}
+
+/// The sentence that points at the file the whole of bug o was about. Only
+/// hung on the message that has two different attempts behind it, because that
+/// is the one where the log holds something the message cannot.
+const LOG_FILE_NOTE: &str =
+ " The log file under Settings, Troubleshoot carries the full command line of both attempts and the engine's own output.";
+
/// One English sentence a user can act on, plus llama-server's own last words
/// so a bug report still carries them.
///
@@ -1255,12 +1457,18 @@ pub(crate) fn with_note_on_top(message: &str, note: &str) -> String {
/// driver or engine build that does not know it fails at load time, and
/// setting GPU Layers to 0 is the one setting in this app that gets the user
/// chatting anyway.
-pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: Duration) -> String {
+pub(crate) fn start_failure_message(
+ failure: &StartFailure,
+ port: u16,
+ budget: Duration,
+ second: SecondAttempt,
+) -> String {
let head = if failure.port_taken {
format!(
"Port {port} answers health checks, but the engine this app just started exited immediately. Another llama-server (likely left over from a previous session or crash) is occupying the port. Quit that process or reboot, then try again."
)
} else if failure.died
+ && second == SecondAttempt::SameOffload
&& stderr_names_a_missing_system_library(&failure.stderr).is_none()
&& stderr_blames_the_gpu(&failure.stderr)
&& !stderr_blames_the_port(&failure.stderr)
@@ -1281,6 +1489,11 @@ pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: D
// auto-fit path, whose line carries the words "device memory", so a
// GGUF with a header it cannot parse used to arrive here and be sent
// away as a graphics-card problem. No setting repairs a broken file.
+ //
+ // And the whole branch is asked only of a retry that ran the SAME
+ // offload. Once the second attempt has run on the processor by itself,
+ // "set GPU Layers to 0" is advice the app has already taken, and
+ // repeating it sends the user to a switch that will change nothing.
format!("The LU Engine started and exited again before it could serve on port {port}. It was tried twice. This looks like a graphics-card problem. Open Settings, LU Engine and set GPU Layers to 0 to run on the CPU, then try again.")
} else if failure.died && stderr_blames_the_port(&failure.stderr) {
format!(
@@ -1294,7 +1507,17 @@ pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: D
} else {
" Reinstall Locally Uncensored if this keeps happening, or pick a different backend in Settings, AI Backends.".to_string()
};
- format!("The LU Engine started and exited again before it could serve on port {port}. It was tried twice.{hint}")
+ match second {
+ SecondAttempt::SameOffload => format!(
+ "The LU Engine started and exited again before it could serve on port {port}. It was tried twice.{hint}"
+ ),
+ // The card has already been taken out of the picture once, so the
+ // sentence says so: there is no setting left for this user to try,
+ // and the next useful thing anyone can do is read the log.
+ SecondAttempt::CpuOnly => format!(
+ "The LU Engine exited before serving on port {port}. Tried with GPU offload and again on CPU.{hint}{LOG_FILE_NOTE}"
+ ),
+ }
} else {
format!(
"The LU Engine did not become healthy on port {port} within {}s (the budget scales with model size, and huge GGUFs can take minutes on a cold first load).",
@@ -1410,8 +1633,21 @@ fn start_bundled_engine_blocking(
engine.port,
slot_dir.as_deref(),
mmproj.as_deref(),
+ None,
);
- if engine.args == args_on_its_port
+ // With GPU Layers on auto the layer count is a MEASUREMENT, taken
+ // after the old engine was stopped and the render caches were
+ // freed, so it cannot be reproduced here and it is not part of the
+ // request. Comparing it would restart a perfectly healthy engine
+ // every time a browser tab changed how much memory was free. A
+ // switch between auto and a typed number is still a real
+ // difference, which is what `auto_layers` on both sides is for.
+ let same_request = if tuning.gpu_layers < 0 && engine.auto_layers {
+ argv_without_gpu_layers(&engine.args) == argv_without_gpu_layers(&args_on_its_port)
+ } else {
+ engine.args == args_on_its_port
+ };
+ if same_request
&& may_keep_engine_where_it_is(engine.port, port, || port_is_bindable(port))
&& engine_healthy(engine.port)
{
@@ -1437,6 +1673,7 @@ fn start_bundled_engine_blocking(
guard.as_ref().map(|e| PreviousEngine {
model_path: e.model_path.clone(),
args: e.args.clone(),
+ auto_layers: e.auto_layers,
port: e.port,
ctx: e.ctx,
})
@@ -1463,6 +1700,10 @@ struct PreviousEngine {
args: Vec<String>,
port: u16,
ctx: Option<u32>,
+ /// Whether that engine's layer count was measured. Carried so the restored
+ /// process is the same kind of start it was, and the idempotence check
+ /// keeps answering the same way about it afterwards.
+ auto_layers: bool,
}
/// Der Satz, der an die Fehlermeldung geht, wenn das alte Modell wieder laeuft.
@@ -1486,6 +1727,7 @@ fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine) -> b
&vorher.model_path,
vorher.port,
vorher.ctx,
+ vorher.auto_layers,
)
.is_ok();
if !ok {
@@ -1605,12 +1847,48 @@ fn start_after_stop(
if port != preferred_port {
tracing::warn!(target: "engine", wanted = preferred_port, port, "the preferred port is taken, the LU Engine moves");
}
+ // The layer count, decided against the card instead of assumed (bugs u and
+ // a). Only for the auto default: a number typed into Settings is the
+ // user's answer and the probe is not even run for it.
+ //
+ // Asked HERE and not further up, for the same reason the port is: the old
+ // engine has been stopped and ComfyUI and Ollama have been asked to let go
+ // a few lines above, so this is the first moment at which "free" means
+ // free. Those two release asynchronously, so a reading taken while a
+ // driver still holds their pages is too small rather than too large, and
+ // too small costs speed while too large costs the start.
+ let ctx_size = effective_ctx(tuning);
+ let auto_layers = tuning.gpu_layers < 0;
+ let auto_ngl = if auto_layers {
+ let card = crate::commands::gpu::engine_vram_reading();
+ let header = crate::commands::gguf::read_header(model_path);
+ let plan = plan_offload(&OffloadInputs {
+ model_bytes: std::fs::metadata(model_path).map(|m| m.len()).unwrap_or(0),
+ block_count: header.block_count,
+ vram_bytes: card.as_ref().map(|c| c.bytes),
+ ctx: ctx_size,
+ });
+ tracing::info!(
+ target: "engine",
+ vram_mib = card.as_ref().map(|c| (c.bytes / (1024 * 1024)).to_string()).unwrap_or_else(|| "unknown".into()),
+ vram_is_free_memory = card.as_ref().map(|c| c.free).unwrap_or(false),
+ vram_source = card.as_ref().map(|c| c.source).unwrap_or("none"),
+ block_count = header.block_count.map(|b| b.to_string()).unwrap_or_else(|| "unknown".into()),
+ ctx = ctx_size,
+ ngl = plan.layers.map(|l| l.to_string()).unwrap_or_else(|| ALL_LAYERS.to_string()),
+ "{}",
+ plan.why
+ );
+ plan.layers
+ } else {
+ None
+ };
let desired_args =
- build_server_args(model_path, tuning, port, slot_dir, mmproj);
+ build_server_args(model_path, tuning, port, slot_dir, mmproj, auto_ngl);
let deadline = health_timeout_for(model_path);
- let ctx = Some(effective_ctx(tuning));
- let first = spawn_engine_attempt(state, &binary, &desired_args, model_path, port, ctx);
+ let ctx = Some(ctx_size);
+ let first = spawn_engine_attempt(state, &binary, &desired_args, model_path, port, ctx, auto_layers);
let failure = match first {
Ok(()) => {
tracing::info!(target: "engine", port, attempt = 1, "the LU Engine is serving");
@@ -1627,7 +1905,7 @@ fn start_after_stop(
if !failure.died {
// The budget ran out with the child still alive: it is loading slowly,
// not failing. Retrying would just spend the budget twice.
- return Err(start_failure_message(&failure, port, deadline));
+ return Err(start_failure_message(&failure, port, deadline, SecondAttempt::SameOffload));
}
tracing::warn!(target: "engine", port, "the first start attempt exited before it served, retrying once");
@@ -1646,30 +1924,62 @@ fn start_after_stop(
} else {
port
};
- let retry_args = if retry_port == port {
- desired_args.clone()
- } else {
+ if retry_port != port {
tracing::warn!(target: "engine", port, retry_port, "the first attempt could not open the port, the retry moves");
- build_server_args(
- model_path,
- tuning,
- retry_port,
- slot_dir,
- mmproj,
- )
+ }
+
+ // The retry used to run the SAME arguments on the same card, which is what
+ // the sentence "It was tried twice" was really saying: twice the wait for
+ // one experiment. If layers went onto a graphics card and the process died
+ // before it served, the card is the first thing worth taking out of the
+ // picture, so the second attempt runs on the processor. Slower, and it
+ // serves. When the first attempt was already on the processor there is
+ // nothing to take away and the retry stays what it was.
+ let offload_was_tried = gpu_layers_in(&desired_args).is_some_and(|n| n > 0);
+ let second_attempt = if offload_was_tried {
+ SecondAttempt::CpuOnly
+ } else {
+ SecondAttempt::SameOffload
};
- match spawn_engine_attempt(state, &binary, &retry_args, model_path, retry_port, ctx) {
+ let retry_args = if offload_was_tried {
+ tracing::warn!(
+ target: "engine",
+ port = retry_port,
+ "the retry drops GPU offload and runs the LU Engine on the processor"
+ );
+ let on_the_cpu = EngineTuning { gpu_layers: 0, ..tuning.clone() };
+ build_server_args(model_path, &on_the_cpu, retry_port, slot_dir, mmproj, None)
+ } else if retry_port != port {
+ build_server_args(model_path, tuning, retry_port, slot_dir, mmproj, auto_ngl)
+ } else {
+ desired_args.clone()
+ };
+ // A retry that ran on the processor was not an auto layer count, whatever
+ // the request said, so the idempotence check must not treat it as one: the
+ // next start with the same settings has to be allowed to try the card
+ // again.
+ let retry_auto = auto_layers && !offload_was_tried;
+ match spawn_engine_attempt(state, &binary, &retry_args, model_path, retry_port, ctx, retry_auto) {
Ok(()) => {
- tracing::info!(target: "engine", port = retry_port, attempt = 2, "the LU Engine is serving");
+ if offload_was_tried {
+ tracing::warn!(
+ target: "engine",
+ port = retry_port,
+ "the LU Engine is serving on the processor only, the graphics card was taken out after the first attempt died"
+ );
+ } else {
+ tracing::info!(target: "engine", port = retry_port, attempt = 2, "the LU Engine is serving");
+ }
Ok(serde_json::json!({
"status": "started",
"port": retry_port,
"model_path": model_path,
"ctx": ctx,
"retried": true,
+ "cpuOnly": offload_was_tried,
}))
}
- Err(second) => Err(start_failure_message(&second, retry_port, deadline)),
+ Err(second) => Err(start_failure_message(&second, retry_port, deadline, second_attempt)),
}
}
@@ -1688,6 +1998,7 @@ pub(crate) struct StartFailure {
/// Spawn the engine and wait for it, watching BOTH the health endpoint and the
/// child. Reaps the child on every failure path so no half-loaded server is
/// left behind.
+#[allow(clippy::too_many_arguments)]
fn spawn_engine_attempt(
state: &AppState,
binary: &Path,
@@ -1695,6 +2006,7 @@ fn spawn_engine_attempt(
model_path: &str,
port: u16,
ctx: Option<u32>,
+ auto_layers: bool,
) -> Result<(), StartFailure> {
// The one line a support log has to carry. Everything the start depends on
// is in the argv: model path, context size, layer count, cache types,
@@ -1754,6 +2066,7 @@ fn spawn_engine_attempt(
port,
ctx,
args: args.to_vec(),
+ auto_layers,
});
let outcome = wait_for_health_or_exit(state, port, health_timeout_for(model_path));
@@ -2587,7 +2900,11 @@ fn start_bundled_embed_blocking(
// No --ctx-size on the embed server; args recorded for symmetry (its
// idempotence check stays model_path-based, embeds have no tuning).
ctx: None,
- args: build_embed_args(&model_path, port),
+ args: embed_args,
+ // The embeddings server sends a fixed `-ngl 999` and nothing measures
+ // anything for it: these models are a few hundred MiB and fit on
+ // whatever is there.
+ auto_layers: false,
});
if let Err(e) = wait_for_health(port, health_timeout_for(&model_path)) {
@@ -2748,10 +3065,10 @@ mod tests {
#[test]
fn slot_save_dir_appends_the_flag_and_none_stays_legacy() {
// GH #85: the KV-slot flag rides at the end so every earlier pin holds.
- let with = build_server_args("/m.gguf", &EngineTuning::default(), 8127, Some("/data/kv-slots"), None);
+ let with = build_server_args("/m.gguf", &EngineTuning::default(), 8127, Some("/data/kv-slots"), None, None);
let tail: Vec<&str> = with.iter().rev().take(2).map(String::as_str).collect();
assert_eq!(tail, vec!["/data/kv-slots", "--slot-save-path"]);
- let without = build_server_args("/m.gguf", &EngineTuning::default(), 8127, None, None);
+ let without = build_server_args("/m.gguf", &EngineTuning::default(), 8127, None, None, None);
assert!(!without.iter().any(|a| a == "--slot-save-path"));
}
@@ -2759,7 +3076,7 @@ mod tests {
fn default_tuning_args_match_legacy_shape() {
// Pin: absent/default tuning must produce EXACTLY the argv the app has
// shipped since 2.5.7 — expert settings are opt-in, never a drift.
- let args = build_server_args("/models/qwen.gguf", &EngineTuning::default(), 8127, None, None);
+ let args = build_server_args("/models/qwen.gguf", &EngineTuning::default(), 8127, None, None, None);
assert_eq!(
args,
vec![
@@ -2780,12 +3097,13 @@ mod tests {
8127,
None,
Some("/models/qwen3.8.mmproj.gguf"),
+ None,
);
let at = with.iter().position(|a| a == "--mmproj").expect("--mmproj missing");
assert_eq!(with[at + 1], "/models/qwen3.8.mmproj.gguf");
// Negative control: a model without a projector keeps the legacy argv,
// so a text-only model can never gain a flag it cannot honour.
- let without = build_server_args("/models/qwen3.8.gguf", &EngineTuning::default(), 8127, None, None);
+ let without = build_server_args("/models/qwen3.8.gguf", &EngineTuning::default(), 8127, None, None, None);
assert!(!without.iter().any(|a| a == "--mmproj"));
assert_eq!(without.len(), with.len() - 2);
}
@@ -2800,6 +3118,7 @@ mod tests {
8127,
Some("/data/kv-slots"),
Some("/m.mmproj.gguf"),
+ None,
);
let tail: Vec<&str> = args.iter().rev().take(2).map(String::as_str).collect();
assert_eq!(tail, vec!["/data/kv-slots", "--slot-save-path"]);
@@ -2912,7 +3231,7 @@ mod tests {
mlock: true,
no_mmap: true,
};
- let args = build_server_args("/m.gguf", &tuning, 8127, None, None);
+ let args = build_server_args("/m.gguf", &tuning, 8127, None, None, None);
assert_eq!(
args,
vec![
@@ -2953,6 +3272,7 @@ mod tests {
8129,
Some("/slots"),
Some("/models/Nemo 12B.mmproj.gguf"),
+ None,
);
let line = command_line(Path::new("/opt/lu/lu-llama-server"), &args);
@@ -2987,7 +3307,7 @@ mod tests {
// made.
let line = command_line(
Path::new("/opt/lu/lu-llama-server"),
- &build_server_args("/m.gguf", &EngineTuning::default(), 8127, None, None),
+ &build_server_args("/m.gguf", &EngineTuning::default(), 8127, None, None, None),
);
for unwanted in ["-ctk", "-ctv", "-fa", "-t ", "--mlock", "--no-mmap", "--mmproj", "--slot-save-path"] {
assert!(!line.contains(unwanted), "{unwanted:?} invented in:\n{line}");
@@ -2995,6 +3315,218 @@ mod tests {
assert!(line.contains("-ngl 999"), "{line}");
}
+ // ── Bugs u and a: how much of a model goes on the card ────────────────
+ //
+ // Every number below is a real one. None of them was measured on the
+ // hardware that reported the bugs: there is no 2 GB and no 8 GB NVIDIA
+ // card on this machine. What these tests prove is the arithmetic and the
+ // direction of every rounding in it, not the effect on a reporter's box.
+
+ /// A 3B Q4_K_M, the size class of the model behind GitHub 128.
+ const THREE_B_Q4: u64 = 2_019_377_696;
+ /// Its layer count.
+ const THREE_B_BLOCKS: u32 = 28;
+ /// A 12B IQ4_XS, the size class behind Discord ticket-0009.
+ const TWELVE_B_IQ4: u64 = 7_300_000_000;
+ const TWELVE_B_BLOCKS: u32 = 40;
+ /// What a 2 GB card, an 8 GB RTX 4060 and a 12 GB RTX 3060 report.
+ const CARD_2_GB: u64 = 2048 * 1024 * 1024;
+ const CARD_8_GB: u64 = 8188 * 1024 * 1024;
+ const CARD_12_GB: u64 = 12288 * 1024 * 1024;
+
+ fn plan(model: u64, blocks: Option<u32>, vram: Option<u64>, ctx: u32) -> OffloadPlan {
+ plan_offload(&OffloadInputs {
+ model_bytes: model,
+ block_count: blocks,
+ vram_bytes: vram,
+ ctx,
+ })
+ }
+
+ #[test]
+ fn a_model_that_fits_is_left_exactly_as_it_was() {
+ // The rule this whole change lives under. A 3B on a 12 GB card has
+ // room for its weights, its cache and the driver, so nothing about
+ // that start may move.
+ let p = plan(THREE_B_Q4, Some(THREE_B_BLOCKS), Some(CARD_12_GB), 8192);
+ assert_eq!(p.layers, None, "{}", p.why);
+ assert!(p.why.contains("every layer is requested"), "{}", p.why);
+ }
+
+ #[test]
+ fn a_card_nothing_measured_keeps_todays_behaviour() {
+ // Apple, a machine without vendor tools, a wedged driver. `None` is a
+ // real answer and it has to mean "carry on as before", or this change
+ // would take the graphics card away from everyone it cannot see.
+ let p = plan(TWELVE_B_IQ4, Some(TWELVE_B_BLOCKS), None, 8192);
+ assert_eq!(p.layers, None);
+ assert!(p.why.contains("no probe measured"), "{}", p.why);
+ }
+
+ #[test]
+ fn a_twelve_b_on_an_eight_gb_card_gets_a_layer_count_instead_of_all_of_them() {
+ // Discord ticket-0009. 7.3 GB of weights plus 1.25 GB of cache at 8192
+ // tokens plus the driver is more than the 8 GB board has, so the whole
+ // model was never going to fit and `-ngl 999` was asking for it anyway.
+ let p = plan(TWELVE_B_IQ4, Some(TWELVE_B_BLOCKS), Some(CARD_8_GB), 8192);
+ assert_eq!(p.layers, Some(37), "{}", p.why);
+ assert!(p.why.contains("40 layers the GGUF header names"), "{}", p.why);
+
+ // And what it chose really does fit in what it measured.
+ let per_layer = TWELVE_B_IQ4 / TWELVE_B_BLOCKS as u64 + 4 * 1024 * 1024 * 8;
+ assert!(37 * per_layer + VRAM_OVERHEAD_BYTES <= CARD_8_GB);
+ assert!(38 * per_layer + VRAM_OVERHEAD_BYTES > CARD_8_GB, "one layer short of the truth");
+ }
+
+ #[test]
+ fn the_counter_check_the_old_code_would_have_sent_all_of_them() {
+ // The same 8 GB case with the new decision switched off, which is what
+ // `auto_ngl: None` is: the argv is the one that shipped, `-ngl 999`.
+ // Without this the test above proves an arithmetic nobody asked for.
+ let tuning = EngineTuning::default();
+ assert_eq!(tuning.gpu_layers, -1, "the default is auto");
+ let old = build_server_args("/models/nemo-12b.gguf", &tuning, 8127, None, None, None);
+ assert_eq!(gpu_layers_in(&old), Some(999));
+
+ let plan = plan(TWELVE_B_IQ4, Some(TWELVE_B_BLOCKS), Some(CARD_8_GB), 8192);
+ let now = build_server_args("/models/nemo-12b.gguf", &tuning, 8127, None, None, plan.layers);
+ assert_eq!(gpu_layers_in(&now), Some(37));
+ // Nothing else about the argv moved.
+ assert_eq!(argv_without_gpu_layers(&old), argv_without_gpu_layers(&now));
+ }
+
+ #[test]
+ fn a_three_b_on_a_two_gb_card_stops_asking_for_the_whole_model() {
+ // GitHub 128 and the two Discord reports. 2 GB of card, about 2 GB of
+ // weights, and a cache on top.
+ let p = plan(THREE_B_Q4, Some(THREE_B_BLOCKS), Some(CARD_2_GB), 8192);
+ assert_eq!(p.layers, Some(15), "{}", p.why);
+ let per_layer = THREE_B_Q4 / THREE_B_BLOCKS as u64 + 4 * 1024 * 1024 * 8;
+ assert!(15 * per_layer + VRAM_OVERHEAD_BYTES <= CARD_2_GB);
+ assert!(16 * per_layer + VRAM_OVERHEAD_BYTES > CARD_2_GB);
+ }
+
+ #[test]
+ fn a_smaller_context_pays_for_fewer_layers_of_cache_and_buys_more_layers() {
+ // The reserve is derived from the context, so the same card and the
+ // same model at 2048 tokens has room for more of the model.
+ let wide = plan(THREE_B_Q4, Some(THREE_B_BLOCKS), Some(CARD_2_GB), 8192);
+ let narrow = plan(THREE_B_Q4, Some(THREE_B_BLOCKS), Some(CARD_2_GB), 2048);
+ assert_eq!(narrow.layers, Some(20), "{}", narrow.why);
+ assert!(narrow.layers > wide.layers);
+ }
+
+ #[test]
+ fn a_header_without_a_layer_count_guesses_low_and_says_that_it_guessed() {
+ // The fallback. 16 assumed layers against a model that really has 28
+ // buys 10 layers where the truth would have bought 15, and 10 layers
+ // of a 28 layer model really do fit. The guess is low ON PURPOSE: the
+ // count only multiplies the fraction that fits, so guessing under the
+ // real block count can only ask for too few layers, never too many.
+ let guessed = plan(THREE_B_Q4, None, Some(CARD_2_GB), 8192);
+ assert_eq!(guessed.layers, Some(10), "{}", guessed.why);
+ assert!(guessed.why.contains("carries no block count"), "{}", guessed.why);
+
+ let real_per_layer = THREE_B_Q4 / THREE_B_BLOCKS as u64 + 4 * 1024 * 1024 * 8;
+ assert!(10 * real_per_layer + VRAM_OVERHEAD_BYTES <= CARD_2_GB, "the guess overshot");
+
+ // A header that answers zero is a header that answered nothing.
+ assert_eq!(plan(THREE_B_Q4, Some(0), Some(CARD_2_GB), 8192), guessed);
+ }
+
+ #[test]
+ fn a_card_far_too_small_ends_up_on_the_processor_rather_than_at_a_bad_number() {
+ // 512 MiB of memory cannot hold the driver's own reserve, let alone a
+ // layer. Zero is the right answer and `saturating_sub` is why it is
+ // not a panic.
+ let p = plan(THREE_B_Q4, Some(THREE_B_BLOCKS), Some(256 * 1024 * 1024), 8192);
+ assert_eq!(p.layers, Some(0), "{}", p.why);
+ }
+
+ #[test]
+ fn a_typed_layer_count_beats_every_measurement() {
+ // The expert's setting is an answer, not a suggestion. `auto_ngl` is
+ // only ever consulted for the auto default.
+ let tuning = EngineTuning { gpu_layers: 20, ..Default::default() };
+ let args = build_server_args("/m.gguf", &tuning, 8127, None, None, Some(3));
+ assert_eq!(gpu_layers_in(&args), Some(20));
+ let cpu = EngineTuning { gpu_layers: 0, ..Default::default() };
+ assert_eq!(
+ gpu_layers_in(&build_server_args("/m.gguf", &cpu, 8127, None, None, Some(3))),
+ Some(0)
+ );
+ }
+
+ #[test]
+ fn the_idempotence_key_ignores_a_measurement_but_not_a_setting() {
+ // Two auto starts a minute apart measure different free memory. That
+ // is not a reason to tear down a healthy engine, and comparing the
+ // whole argv would have made it one. A switch between auto and a typed
+ // number still has to read as a different request.
+ let auto = EngineTuning::default();
+ let a = build_server_args("/m.gguf", &auto, 8127, None, None, Some(35));
+ let b = build_server_args("/m.gguf", &auto, 8127, None, None, Some(33));
+ assert_ne!(a, b);
+ assert_eq!(argv_without_gpu_layers(&a), argv_without_gpu_layers(&b));
+
+ // A model swap is still a difference with the layers stripped out.
+ let other = build_server_args("/other.gguf", &auto, 8127, None, None, Some(35));
+ assert_ne!(argv_without_gpu_layers(&a), argv_without_gpu_layers(&other));
+ // And so is a context change.
+ let wider = EngineTuning { ctx: 16384, ..Default::default() };
+ assert_ne!(
+ argv_without_gpu_layers(&a),
+ argv_without_gpu_layers(&build_server_args("/m.gguf", &wider, 8127, None, None, Some(35)))
+ );
+ }
+
+ #[test]
+ fn the_second_attempt_says_that_it_ran_on_the_processor() {
+ // The old message said "It was tried twice" about two identical
+ // attempts. When the retry really did drop the card, the sentence has
+ // to say so, and it must not go on to advise a setting the app has
+ // already used up.
+ let out_of_memory = StartFailure {
+ died: true,
+ port_taken: false,
+ stderr: "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 9216.00 MiB on device 0: cudaMalloc failed: out of memory".into(),
+ };
+ let same = start_failure_message(&out_of_memory, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
+ assert!(same.contains("It was tried twice"), "{same}");
+ assert!(same.contains("set GPU Layers to 0"), "{same}");
+
+ let cpu = start_failure_message(&out_of_memory, 8127, Duration::from_secs(60), SecondAttempt::CpuOnly);
+ assert!(cpu.contains("The LU Engine exited before serving on port 8127."), "{cpu}");
+ assert!(cpu.contains("Tried with GPU offload and again on CPU."), "{cpu}");
+ assert!(!cpu.contains("GPU Layers"), "the way out was already taken:\n{cpu}");
+ assert!(cpu.contains("Settings, Troubleshoot"), "{cpu}");
+ // The engine's own last words still ride along for a bug report.
+ assert!(cpu.contains("cudaMalloc failed"), "{cpu}");
+ }
+
+ #[test]
+ fn a_retry_on_the_processor_is_only_offered_when_there_was_offload_to_drop() {
+ // What `start_after_stop` reads to decide. A first attempt that was
+ // already on the processor has nothing left to take away, so its
+ // message keeps the old wording.
+ let auto = EngineTuning::default();
+ assert_eq!(
+ gpu_layers_in(&build_server_args("/m.gguf", &auto, 8127, None, None, None)),
+ Some(999)
+ );
+ let already_cpu = EngineTuning { gpu_layers: 0, ..Default::default() };
+ assert_eq!(
+ gpu_layers_in(&build_server_args("/m.gguf", &already_cpu, 8127, None, None, None)),
+ Some(0)
+ );
+ // A measured zero is the same case: the card is already out.
+ assert_eq!(
+ gpu_layers_in(&build_server_args("/m.gguf", &auto, 8127, None, None, Some(0))),
+ Some(0)
+ );
+ assert_eq!(gpu_layers_in(&["--port".to_string(), "8127".to_string()]), None);
+ }
+
#[test]
fn nothing_in_this_module_writes_to_a_stream_the_user_cannot_send() {
// Bug o, and the guard against it coming back. A shipped Windows build
@@ -3046,7 +3578,7 @@ mod tests {
mlock: false,
no_mmap: false,
};
- let args = build_server_args("/m.gguf", &tuning, 8127, None, None);
+ let args = build_server_args("/m.gguf", &tuning, 8127, None, None, None);
assert_eq!(
args,
vec![
@@ -3062,7 +3594,7 @@ mod tests {
#[test]
fn gpu_layers_zero_means_cpu_only_not_all() {
let tuning = EngineTuning { gpu_layers: 0, ..Default::default() };
- let args = build_server_args("/m.gguf", &tuning, 8127, None, None);
+ let args = build_server_args("/m.gguf", &tuning, 8127, None, None, None);
let ngl = args.iter().position(|a| a == "-ngl").unwrap();
assert_eq!(args[ngl + 1], "0");
}
@@ -3611,6 +4143,7 @@ mod tests {
port: DEAD_PORT,
ctx: Some(8192),
args: Vec::new(),
+ auto_layers: false,
});
}
@@ -3692,6 +4225,7 @@ mod tests {
let vorher = PreviousEngine {
model_path: "/tmp/hermes.gguf".into(),
args: vec!["-c".into(), "sleep 30".into()],
+ auto_layers: false,
port,
ctx: Some(8192),
};
@@ -3733,6 +4267,7 @@ mod tests {
let vorher = PreviousEngine {
model_path: "/tmp/hermes.gguf".into(),
args: vec!["-c".into(), "exit 1".into()],
+ auto_layers: false,
port: DEAD_PORT,
ctx: Some(8192),
};
@@ -3793,7 +4328,7 @@ mod tests {
stderr: KAPUTTE_VERSION_STDERR.into(),
};
let msg = with_note_on_top(
- &start_failure_message(&f, 8127, Duration::from_secs(60)),
+ &start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload),
RESTORED_NOTE,
);
let notiz = msg.find(RESTORED_NOTE).expect("the note is gone");
@@ -3836,6 +4371,7 @@ mod tests {
port,
ctx: Some(8192),
args: Vec::new(),
+ auto_layers: false,
})
}
@@ -4091,7 +4627,7 @@ mod tests {
port_taken: false,
stderr: "bind: Address already in use".into(),
};
- let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("could not open port 8127"), "{msg}");
assert!(
!msg.contains("Reinstall"),
@@ -4103,7 +4639,7 @@ mod tests {
port_taken: false,
stderr: "something went wrong".into(),
};
- assert!(start_failure_message(&other, 8127, Duration::from_secs(60)).contains("Reinstall"));
+ assert!(start_failure_message(&other, 8127, Duration::from_secs(60), SecondAttempt::SameOffload).contains("Reinstall"));
}
#[test]
@@ -4116,7 +4652,7 @@ mod tests {
assert!(!stderr_blames_the_port(oom));
assert!(stderr_blames_the_gpu(oom));
let failure = StartFailure { died: true, port_taken: false, stderr: oom.into() };
- let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("GPU Layers to 0"), "the way out has to survive: {msg}");
assert!(!msg.contains("could not open port"), "{msg}");
}
@@ -4151,7 +4687,7 @@ mod tests {
// out of the graphics-card answer.
assert!(!stderr_blames_the_gpu(stderr), "a banner is not a defect");
let failure = StartFailure { died: true, port_taken: false, stderr: stderr.into() };
- let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("could not open port 8127"), "{msg}");
assert!(!msg.contains("GPU Layers"), "a busy port is not freed by CPU mode: {msg}");
}
@@ -4193,7 +4729,7 @@ mod tests {
// its budget spends the same budget again (up to 10 minutes on a big
// GGUF) and re-runs the ComfyUI and Ollama evictions each time.
let slow = StartFailure { died: false, port_taken: false, stderr: String::new() };
- let msg = start_failure_message(&slow, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&slow, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(
msg.contains("did not become healthy"),
"the frontend matches on this phrase: {msg}"
@@ -4207,7 +4743,7 @@ mod tests {
"something went wrong",
] {
let died = StartFailure { died: true, port_taken: false, stderr: stderr.into() };
- let m = start_failure_message(&died, 8127, Duration::from_secs(60));
+ let m = start_failure_message(&died, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(!m.contains("did not become healthy"), "{m}");
}
}
@@ -4264,7 +4800,7 @@ mod tests {
port_taken: false,
stderr: "ggml_cuda_init: failed to initialize CUDA: no kernel image is available for execution on the device".into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("exited again"), "{msg}");
assert!(msg.contains("tried twice"), "{msg}");
assert!(msg.contains("GPU Layers to 0"), "{msg}");
@@ -4279,7 +4815,7 @@ mod tests {
port_taken: false,
stderr: "llama_model_load: error loading model: unknown model architecture 'wanx'".into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("could not read the model file"), "{msg}");
assert!(!msg.contains("GPU Layers"), "{msg}");
}
@@ -4308,7 +4844,7 @@ srv llama_server: exiting due to model loading error";
port_taken: false,
stderr: KAPUTTE_GGUF_STDERR.into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("could not read the model file"), "{msg}");
assert!(!msg.contains("GPU Layers"), "{msg}");
assert!(!msg.contains("graphics-card"), "{msg}");
@@ -4526,7 +5062,7 @@ srv llama_server: exiting due to model loading error";
port_taken: false,
stderr: KAPUTTE_VERSION_STDERR.into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("could not read the model file"), "{msg}");
assert!(!msg.contains("GPU Layers"), "{msg}");
assert!(!msg.contains("graphics-card"), "{msg}");
@@ -4543,7 +5079,7 @@ srv llama_server: exiting due to model loading error";
port_taken: false,
stderr: "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 9216.00 MiB on device 0: cudaMalloc failed: out of memory\nllama_model_load: error loading model: unable to allocate CUDA0 buffer\nllama_model_load_from_file_impl: failed to load model".into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("GPU Layers"), "{msg}");
assert!(!msg.contains("could not read the model file"), "{msg}");
}
@@ -4551,7 +5087,7 @@ srv llama_server: exiting due to model loading error";
#[test]
fn a_stranger_on_the_port_keeps_its_own_message() {
let f = StartFailure { died: true, port_taken: true, stderr: String::new() };
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("occupying the port"), "{msg}");
assert!(!msg.contains("tried twice"), "{msg}");
}
@@ -4559,7 +5095,7 @@ srv llama_server: exiting due to model loading error";
#[test]
fn a_slow_load_still_reports_the_budget_and_never_claims_a_crash() {
let f = StartFailure { died: false, port_taken: false, stderr: String::new() };
- let msg = start_failure_message(&f, 8127, Duration::from_secs(220));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(220), SecondAttempt::SameOffload);
assert!(msg.contains("did not become healthy on port 8127 within 220s"), "{msg}");
assert!(!msg.contains("exited"), "{msg}");
}
@@ -4577,7 +5113,7 @@ srv llama_server: exiting due to model loading error";
port_taken: false,
stderr: "lu-llama-server: error while loading shared libraries: libvulkan.so.1: cannot open shared object file: No such file or directory".into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("libvulkan.so.1"), "{msg}");
assert!(!msg.contains("GPU Layers"), "{msg}");
// The engine's own last words still ride along for a bug report.
@@ -4663,7 +5199,7 @@ srv llama_server: exiting due to model loading error";
port_taken: false,
stderr: "ggml_vulkan: no devices found".into(),
};
- let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60), SecondAttempt::SameOffload);
assert!(msg.contains("GPU Layers to 0"), "{msg}");
assert!(!msg.contains("apt install"), "{msg}");
// And an empty stderr names no library at all.
diff --git a/src-tauri/src/commands/gguf.rs b/src-tauri/src/commands/gguf.rs
index ab721021..7f13b1f5 100644
--- a/src-tauri/src/commands/gguf.rs
+++ b/src-tauri/src/commands/gguf.rs
@@ -7,6 +7,11 @@
//! Context dropdown uses it to cap its presets — without it a 32k model
//! happily "accepts" -c 131072 and degrades silently (llama.cpp only warns).
//!
+//! The same header carries `<arch>.block_count`, the number of transformer
+//! layers `-ngl` counts in. The engine start needs it to answer "how much of
+//! this model fits on this card" with a layer count instead of the blanket
+//! 999 that put a 12B model onto an 8 GB board (3.0.0 list, bugs u and a).
+//!
//! Deliberately paranoid: this runs against user-downloaded files inside
//! `list_bundled_models`, so it must NEVER panic or stall the listing —
//! every failure path is `None`, reads are bounded, and only the header is
@@ -118,10 +123,47 @@ fn read_value(r: &mut R, ty: u32) -> Option<Val> {
}
}
+/// The numbers this app reads out of a GGUF header.
+///
+/// Every field is independently optional: a header can name its architecture
+/// and its context length and say nothing about its layers, and a file that
+/// is not a GGUF at all answers with all of them empty rather than an error.
+/// Nothing here is ever a reason to refuse a model.
+#[derive(Debug, Default, PartialEq)]
+pub struct HeaderFacts {
+ /// `<arch>.context_length`, the context the model was TRAINED with.
+ pub context_length: Option<u32>,
+ /// `<arch>.block_count`, how many transformer layers there are to
+ /// offload. This is the denominator of the per-layer size the engine
+ /// start divides the free graphics memory by.
+ pub block_count: Option<u32>,
+}
+
/// The context length the model was TRAINED with (`<arch>.context_length`),
/// or `None` when the file is missing, not GGUF, truncated, or simply does
/// not carry the key. Never panics, never reads past the header.
pub fn context_length(path: &str) -> Option<u32> {
+ // `list_bundled_models` calls this once per file in the models folder and
+ // wants nothing else, so the scan is told it may stop at the first answer.
+ scan_header(path, false).unwrap_or_default().context_length
+}
+
+/// Context length AND layer count in one pass. Costs more than
+/// `context_length` on a file that carries no `block_count`, because the scan
+/// then has to walk past the tokenizer vocabulary before it can say so; the
+/// engine start pays that once per start, not once per listed model.
+pub fn read_header(path: &str) -> HeaderFacts {
+ scan_header(path, true).unwrap_or_default()
+}
+
+/// One bounded pass over the KV block.
+///
+/// `need_blocks` decides when the scan is allowed to stop early. Returns
+/// `None` for anything that is not a readable GGUF header, which the callers
+/// turn into empty facts. A header that ends mid-field is not evidence of
+/// anything, and inventing a number from half a file is how a model gets
+/// loaded with arguments nobody can explain afterwards.
+fn scan_header(path: &str, need_blocks: bool) -> Option<HeaderFacts> {
let file = File::open(path).ok()?;
let mut buf = BufReader::new(file);
let mut r = R(&mut buf);
@@ -143,6 +185,7 @@ pub fn context_length(path: &str) -> Option<u32> {
let mut arch: Option<String> = None;
let mut ctx_by_key: Option<(String, u64)> = None;
+ let mut blocks_by_key: Option<(String, u64)> = None;
for _ in 0..kv_count {
let key = r.string(MAX_STR)?;
@@ -153,20 +196,45 @@ pub fn context_length(path: &str) -> Option<u32> {
Val::UInt(n) if key.ends_with(".context_length") => {
ctx_by_key = Some((key, n));
}
+ Val::UInt(n) if key.ends_with(".block_count") => {
+ blocks_by_key = Some((key, n));
+ }
_ => {}
}
- // Early exit once both halves are known and they agree.
- if let (Some(a), Some((k, n))) = (&arch, &ctx_by_key) {
- if k == &format!("{a}.context_length") {
- return u32::try_from(*n).ok();
+ // Early exit once everything the caller asked for is known and agrees
+ // with the architecture. What follows in a real file is the tokenizer
+ // vocabulary, which is megabytes of skipping for nothing.
+ if let Some(a) = &arch {
+ let ctx_done = matches_arch(&ctx_by_key, a, "context_length");
+ let blocks_done = !need_blocks || matches_arch(&blocks_by_key, a, "block_count");
+ if ctx_done && blocks_done {
+ return Some(HeaderFacts {
+ context_length: resolve(arch.as_deref(), ctx_by_key, "context_length"),
+ block_count: resolve(arch.as_deref(), blocks_by_key, "block_count"),
+ });
}
}
}
- // Architecture key came AFTER the context key (order is unspecified), or
- // the arch never showed up — accept any single *.context_length match.
- match (arch, ctx_by_key) {
- (Some(a), Some((k, n))) if k == format!("{a}.context_length") => u32::try_from(n).ok(),
+ // Architecture key came AFTER the numbers (order is unspecified), or the
+ // arch never showed up. `resolve` accepts a lone match in that case.
+ Some(HeaderFacts {
+ context_length: resolve(arch.as_deref(), ctx_by_key, "context_length"),
+ block_count: resolve(arch.as_deref(), blocks_by_key, "block_count"),
+ })
+}
+
+/// True when `found` is the key this architecture would write.
+fn matches_arch(found: &Option<(String, u64)>, arch: &str, suffix: &str) -> bool {
+ matches!(found, Some((k, _)) if k == &format!("{arch}.{suffix}"))
+}
+
+/// The number, if the key belongs to this model's architecture, or if no
+/// architecture was named at all, in which case a single `*.<suffix>` hit is
+/// the only candidate there is.
+fn resolve(arch: Option<&str>, found: Option<(String, u64)>, suffix: &str) -> Option<u32> {
+ match (arch, found) {
+ (Some(a), Some((k, n))) if k == format!("{a}.{suffix}") => u32::try_from(n).ok(),
(None, Some((_, n))) => u32::try_from(n).ok(),
_ => None,
}
@@ -174,7 +242,7 @@ pub fn context_length(path: &str) -> Option<u32> {
#[cfg(test)]
mod tests {
- use super::context_length;
+ use super::{context_length, read_header, HeaderFacts};
use std::io::Write;
// Tiny hand-rolled GGUF v3 writer — just enough for the header path.
@@ -254,6 +322,59 @@ mod tests {
assert_eq!(context_length(p.to_str().unwrap()), Some(32768));
}
+ #[test]
+ fn reads_the_layer_count_next_to_the_context_length() {
+ // What the engine start divides the file size by. Both numbers come
+ // out of one pass, and the tokenizer array between them is skipped.
+ let dir = fixtures("blocks");
+ let mut w = W::new(5);
+ w.str_field("general.architecture", "llama");
+ w.u32_field("llama.context_length", 8192);
+ w.arr_str_field("tokenizer.ggml.tokens", &["a", "b", "c"]);
+ w.u32_field("llama.block_count", 40);
+ w.str_field("general.name", "unit test model");
+ let p = dir.join("blocks.gguf");
+ w.write_to(&p);
+ assert_eq!(
+ read_header(p.to_str().unwrap()),
+ HeaderFacts { context_length: Some(8192), block_count: Some(40) }
+ );
+ }
+
+ #[test]
+ fn a_header_without_a_layer_count_says_so_instead_of_guessing() {
+ // The engine start has a fallback for this, and the fallback only
+ // works if the reader admits it found nothing. A number invented here
+ // would be spent as if it had been measured.
+ let dir = fixtures("no-blocks");
+ let mut w = W::new(2);
+ w.str_field("general.architecture", "llama");
+ w.u32_field("llama.context_length", 4096);
+ let p = dir.join("no-blocks.gguf");
+ w.write_to(&p);
+ let facts = read_header(p.to_str().unwrap());
+ assert_eq!(facts.context_length, Some(4096));
+ assert_eq!(facts.block_count, None);
+
+ // A block count belonging to ANOTHER architecture is not this model's.
+ let mut other = W::new(3);
+ other.str_field("general.architecture", "llama");
+ other.u32_field("llama.context_length", 4096);
+ other.u32_field("qwen2.block_count", 28);
+ let q = dir.join("foreign-blocks.gguf");
+ other.write_to(&q);
+ assert_eq!(read_header(q.to_str().unwrap()).block_count, None);
+ }
+
+ #[test]
+ fn a_file_that_is_not_a_gguf_answers_with_empty_facts() {
+ let dir = fixtures("blocks-garbage");
+ let p = dir.join("garbage.gguf");
+ std::fs::write(&p, b"MZ\x90definitely not a gguf").unwrap();
+ assert_eq!(read_header(p.to_str().unwrap()), HeaderFacts::default());
+ assert_eq!(read_header("/nonexistent/nope.gguf"), HeaderFacts::default());
+ }
+
#[test]
fn context_key_before_architecture_still_resolves() {
let dir = fixtures("reversed");
diff --git a/src-tauri/src/commands/gpu.rs b/src-tauri/src/commands/gpu.rs
index 95005d5f..2a3ca642 100644
--- a/src-tauri/src/commands/gpu.rs
+++ b/src-tauri/src/commands/gpu.rs
@@ -1380,6 +1380,79 @@ pub fn detect_gpus() -> Result<Vec<DetectedGpu>, String> {
Ok(gpus)
}
+/// One MiB, because every vendor tool on this planet reports in MiB and every
+/// caller downstream wants bytes.
+const MIB: u64 = 1024 * 1024;
+
+/// What the engine start is allowed to assume about graphics memory.
+#[derive(Debug, Clone, PartialEq)]
+pub struct VramReading {
+ /// Bytes. FREE memory where a probe could measure it, the card's total
+ /// where it could not. The difference matters to the reader of the log
+ /// line, which is why it is carried rather than flattened away.
+ pub bytes: u64,
+ /// True when `bytes` is free memory rather than the card's total.
+ pub free: bool,
+ /// The probe that produced the number, for the log line.
+ pub source: &'static str,
+}
+
+/// `nvidia-smi --query-gpu=memory.free,memory.total --format=csv,noheader,nounits`
+/// writes one line per card: `7423, 8188`. Returns (free, total) in MiB of the
+/// card with the largest total, or `None` when no line parses.
+///
+/// Largest, not first, and not the sum: it mirrors what the rest of the app
+/// already reports as "your VRAM" (`getMaxVramGb` in src/lib/hardware.ts). On a
+/// box with two unequal cards llama.cpp spreads layers over both, so the sum
+/// would be the generous answer and the max is the cautious one. Cautious is
+/// the direction that keeps the engine alive.
+pub(crate) fn parse_nvidia_memory(raw: &str) -> Option<(u64, u64)> {
+ raw.lines()
+ .filter_map(|line| {
+ let mut parts = line.split(',').map(|s| s.trim());
+ let free: u64 = parts.next()?.parse().ok()?;
+ let total: u64 = parts.next()?.parse().ok()?;
+ // A card that reports zero total has not been measured, it has
+ // been guessed at by a driver that is not answering properly.
+ (total > 0 && free <= total).then_some((free, total))
+ })
+ .max_by_key(|(_, total)| *total)
+}
+
+/// How much graphics memory the engine start may plan with, or `None` when
+/// nothing on this machine measured a card.
+///
+/// `None` is a real answer and the callers must keep their old behaviour on
+/// it. Two kinds of machine land there on purpose:
+///
+/// * Apple. `detect_macos` reports no size because there is no separate
+/// card to size: the weights sit in the same memory either way, and the
+/// Metal backend does its own accounting.
+/// * Anything whose vendor tools are missing or wedged.
+///
+/// Cost: `nvidia-smi` answers in milliseconds and fails instantly when it is
+/// not installed, so the common case is cheap. The fallback is the app's full
+/// `detect_gpus` sweep, which is bounded at five seconds per probe; it runs
+/// only on machines without NVIDIA, and only once per engine start.
+pub fn engine_vram_reading() -> Option<VramReading> {
+ // Free, not total: a desktop compositor, a browser and whatever the Create
+ // tab just rendered are all holding pages this engine cannot have. Total
+ // would plan with memory that is not there. The total half of the reading
+ // is only there so `parse_nvidia_memory` can throw out a card whose driver
+ // answers nonsense.
+ if let Some((free, _total)) = run_cmd(
+ "nvidia-smi",
+ &["--query-gpu=memory.free,memory.total", "--format=csv,noheader,nounits"],
+ )
+ .as_deref()
+ .and_then(parse_nvidia_memory)
+ {
+ return Some(VramReading { bytes: free * MIB, free: true, source: "nvidia-smi" });
+ }
+ let biggest = detect_gpus().ok()?.into_iter().filter_map(|g| g.memory_mib).max()?;
+ Some(VramReading { bytes: biggest * MIB, free: false, source: "detect_gpus" })
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpuSelection {
/// Vendor whose env-var family to set ("nvidia" | "amd" | "intel" | "auto").
@@ -1439,6 +1512,27 @@ impl Default for GpuSelection {
mod tests {
use super::*;
+ #[test]
+ fn the_engine_reads_free_memory_off_the_biggest_card() {
+ // Two cards, the second one larger and busier. The plan has to be
+ // made against what is free on the card it would actually use.
+ let raw = "7423, 8188\n2100, 24564\n";
+ assert_eq!(parse_nvidia_memory(raw), Some((2100, 24564)));
+ assert_eq!(parse_nvidia_memory("7423, 8188"), Some((7423, 8188)));
+ }
+
+ #[test]
+ fn a_driver_that_answers_nonsense_measures_nothing() {
+ // Every one of these used to be a number the engine would have
+ // planned with. A zero total is a driver that is not answering, and
+ // free above total is not a reading either.
+ for raw in ["", "N/A, N/A", "0, 0", "8188", "9000, 8188", "[Not Supported]"] {
+ assert_eq!(parse_nvidia_memory(raw), None, "{raw:?}");
+ }
+ // One unreadable line does not throw away the readable one next to it.
+ assert_eq!(parse_nvidia_memory("N/A, N/A\n7423, 8188"), Some((7423, 8188)));
+ }
+
/// Real `reg query … /s /v DriverDesc` shape from a two-GPU box: an Arc Pro
/// alongside a Radeon (bobbyt5667's machine, Discord 2026-07-28).
const DRIVER_DESC_OUT: &str = r"
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 996f3ad4..dd6a54b8 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -48,6 +48,15 @@ pub struct BundledEngine {
/// request resolving to the same argv reuses the running process, any
/// difference (model, ctx, tuning, port) triggers a stop→start.
pub args: Vec<String>,
+ /// True when the layer count inside `args` was MEASURED against the card
+ /// (the "auto" default) rather than typed by the user.
+ ///
+ /// The idempotence key needs the difference. Two auto starts whose
+ /// measurements differ by a few hundred MiB of free memory are the same
+ /// REQUEST and must not tear down a healthy engine over it, while a switch
+ /// between auto and a typed number is a different request even on the days
+ /// the two numbers happen to agree.
+ pub auto_layers: bool,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]