From 394a213520c0054e99a72103ae3150221c26e210 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-models: add catalog module --- crates/capri-models/src/catalog.rs | 369 +++++++++++++++++++++++++++++ 1 file changed, 369 insertions(+) create mode 100644 crates/capri-models/src/catalog.rs diff --git a/crates/capri-models/src/catalog.rs b/crates/capri-models/src/catalog.rs new file mode 100644 index 0000000..eb24d5f --- /dev/null +++ b/crates/capri-models/src/catalog.rs @@ -0,0 +1,369 @@ +//! Capri's model catalog, hardware recommendations and memory planning +//! (`hardware/profiles.mjs`, `model-catalog.mjs`, `memory-budget.mjs`, `model-recommendations.mjs`, +//! `config/context-policy.mjs`). +use std::sync::LazyLock; + +use capri_core::Settings; +use capri_llm::InferenceSection; +use serde_json::Value; + +use crate::hardware::Hardware; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ModelChoice { + pub id: &'static str, + pub family: &'static str, + /// Upstream registry tag. + pub model: &'static str, + /// Name configured for the conversation (Capri alias for Qwen). + pub alias: &'static str, + pub ram_gib: f64, + pub recommended_vram_gib: f64, + pub context_tokens: u32, + pub context_limit: Option, + pub cpu_threads: u32, + pub voice: &'static str, + /// Declared capabilities; `None` = Qwen (tools, vision, thinking checked on the alias). + pub capabilities: Option<&'static [&'static str]>, + pub experimental: bool, + pub description: &'static str, +} + +#[allow(clippy::too_many_arguments, reason = "one row of the profile table")] +const fn qwen(id: &'static str, model: &'static str, alias: &'static str, ram: f64, vram: f64, threads: u32, voice: &'static str, description: &'static str) -> ModelChoice { + ModelChoice { id, family: "Qwen3.5", model, alias, ram_gib: ram, recommended_vram_gib: vram, context_tokens: 32768, context_limit: None, cpu_threads: threads, voice, capabilities: None, experimental: false, description } +} + +/// The four hardware profiles first, then the alternatives (Capri order). +pub const CHOICES: [ModelChoice; 6] = [ + qwen("minimal", "qwen3.5:0.8b", "capri-qwen3.5:0.8b", 8.0, 0.0, 2, "off", "CPU text mode; reduced quality and potentially long replies."), + qwen("balanced", "qwen3.5:2b", "capri-qwen3.5:2b", 16.0, 4.0, 4, "optional", "Text-first default. Ollama may accelerate it when a supported GPU is available."), + qwen("desktop", "qwen3.5:4b", "capri-qwen3.5:4b", 24.0, 8.0, 4, "optional", "Recommended with at least 8 GiB confirmed discrete VRAM; CPU execution is slower."), + qwen("quality", "qwen3.5:9b", "capri-qwen3.5:9b", 32.0, 12.0, 8, "optional", "Existing quality baseline; recommend 12+ GiB confirmed discrete VRAM. Speech uses additional resources."), + ModelChoice { + id: "ministral-3-3b", + family: "Ministral 3", + model: "ministral-3:3b", + alias: "ministral-3:3b", + ram_gib: 16.0, + recommended_vram_gib: 6.0, + context_tokens: 32768, + context_limit: Some(262_144), + cpu_threads: 4, + voice: "optional", + capabilities: Some(&["tools", "vision"]), + experimental: true, + description: "Alternative vision and tool model. Character and tool reliability can differ.", + }, + ModelChoice { + id: "gemma4-e2b", + family: "Gemma 4", + model: "gemma4:e2b", + alias: "gemma4:e2b", + ram_gib: 24.0, + recommended_vram_gib: 12.0, + context_tokens: 32768, + context_limit: Some(131_072), + cpu_threads: 4, + voice: "optional", + capabilities: Some(&["tools", "vision", "thinking"]), + experimental: true, + description: "Alternative multimodal model. Download size and memory use exceed its active parameter count.", + }, +]; + +/// Memory embeddings: `capri-embed:latest` = `bge-m3:latest` with `num_gpu 0` (`config/Embedding.Modelfile`). +pub const EMBEDDING_ALIAS: &str = "capri-embed:latest"; +pub const EMBEDDING_BASE: &str = "bge-m3:latest"; + +static ESTIMATES: LazyLock = LazyLock::new(|| serde_json::from_str(include_str!("../data/memory-estimates.json")).expect("memory estimates")); +static SIZES: LazyLock = LazyLock::new(|| serde_json::from_str(include_str!("../data/qwen-download-sizes.json")).expect("download sizes")); +static BENCHMARK: LazyLock = LazyLock::new(|| serde_json::from_str(include_str!("../data/model-language-benchmark.json")).expect("language benchmark")); + +pub fn choice(id: &str) -> Option<&'static ModelChoice> { + CHOICES.iter().find(|c| c.id == id) +} + +/// Approximate download size in bytes (`config/qwen-download-sizes.json`); local sizes take priority. +pub fn download_size(model: &str) -> Option { + SIZES["models"][model].as_u64() +} + +/// Allows bounded firmware/iGPU reservations (8 → 7.5, 16 → 15, 24 → 22.5, 32 → 30 GiB). +pub fn meets_profile_ram(ram_gib: f64, required_gib: f64) -> bool { + let reservation = (required_gib / 16.0).clamp(0.5, 2.0); + ram_gib.is_finite() && required_gib.is_finite() && required_gib > 0.0 && ram_gib >= required_gib - reservation +} + +/// RAM needed for this choice: the GPU estimate when a dedicated card reaches the threshold. +pub fn profile_ram_requirement(choice: &ModelChoice, hw: &Hardware) -> f64 { + let estimate = &ESTIMATES["models"][choice.id]; + let threshold = if choice.recommended_vram_gib > 0.0 { choice.recommended_vram_gib } else { estimate["vram"][1].as_f64().map_or(f64::INFINITY, f64::ceil) }; + match (estimate["gpuSystemRamGiB"].as_f64(), hw.dedicated_gpu().and_then(|g| g.dedicated_vram_mib())) { + (Some(gpu_ram), Some(vram)) if vram as f64 / 1024.0 >= threshold - 0.125 => gpu_ram, + _ => choice.ram_gib, + } +} + +fn clamp_threads(choice: &ModelChoice, hw: &Hardware) -> u32 { + choice.cpu_threads.min((hw.cpu_threads / 2).max(1)).max(1) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Recommendation { + pub profile: Option<&'static ModelChoice>, + pub cpu_threads: u32, + pub reasons: Vec, +} + +pub fn recommend_profile(hw: &Hardware) -> Recommendation { + let ram = hw.ram_gib(); + if !meets_profile_ram(ram, 8.0) { + return Recommendation { profile: None, cpu_threads: 1, reasons: vec!["The first supported profile requires at least 8 GiB RAM.".into()] }; + } + let vram = hw.dedicated_vram_gib(); + let fits = |i: usize| meets_profile_ram(ram, profile_ram_requirement(&CHOICES[i], hw)); + let index = if fits(3) && vram >= 11.875 { + 3 + } else if fits(2) && vram >= 7.875 { + 2 + } else if fits(1) { + 1 + } else { + 0 + }; + let profile = &CHOICES[index]; + Recommendation { + profile: Some(profile), + cpu_threads: clamp_threads(profile, hw), + reasons: vec![ + format!("Detected {ram:.1} GiB RAM."), + if vram > 0.0 { format!("Largest confirmed dedicated GPU: {vram:.1} GiB.") } else { "Dedicated VRAM is unknown; a conservative text profile is selected.".into() }, + "Ollama decides actual text acceleration. CUDA speech must be installed and checked separately.".into(), + ], + } +} + +/// Checks a catalog choice against the hardware; returns it with the clamped thread count. +pub fn select_model_choice(id: &str, hw: &Hardware) -> Result<(&'static ModelChoice, u32), String> { + let choice = choice(id).ok_or("Unknown language model.")?; + let required = profile_ram_requirement(choice, hw); + if !meets_profile_ram(hw.ram_gib(), required) { + return Err(if CHOICES[..4].contains(choice) { + format!("{id} requires at least {required} GiB RAM for the detected GPU/CPU configuration.") + } else { + "This model needs more system RAM.".into() + }); + } + Ok((choice, clamp_threads(choice, hw))) +} + +/// Up to two benchmarked choices for a conversation language that fit this machine. +pub fn recommend_models_for_language(language: &str, hw: &Hardware) -> Vec<&'static str> { + let vram = hw.dedicated_vram_gib(); + BENCHMARK["recommendations"][language] + .as_array() + .into_iter() + .flatten() + .filter_map(|id| choice(id.as_str()?)) + .filter(|c| meets_profile_ram(hw.ram_gib(), profile_ram_requirement(c, hw)) && (c.recommended_vram_gib <= 4.0 || vram >= c.recommended_vram_gib - 0.125)) + .map(|c| c.id) + .take(2) + .collect() +} + +/// What the owner plans to run, for the memory estimate. +#[derive(Clone, Debug, Default)] +pub struct Selection<'a> { + pub profile: &'a str, + pub download_models: bool, + pub conversation_language: &'a str, + pub recognition: bool, + pub router: bool, + /// `off`, `qwen`, or any other enabled voice. + pub voice_mode: &'a str, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BudgetRow { + pub estimate: [f64; 2], + pub total: Option, + pub available: Option, + pub exceeds_available: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct MemoryBudget { + pub gpu_mode: bool, + pub offload: bool, + pub ram: BudgetRow, + pub vram: BudgetRow, +} + +/// Planning ranges in GiB, not measured guarantees. +pub fn estimate_memory_budget(sel: &Selection<'_>, hw: &Hardware) -> Result { + let e = &*ESTIMATES; + let range = |v: &Value| [v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0)]; + let gpu = hw.dedicated_gpu(); + let mut ram = range(&e["base"]["ram"]); + let mut vram = if gpu.is_some() { range(&e["base"]["vram"]) } else { [0.0; 2] }; + let mut add = |part: &Value| { + let (r, v) = (range(&part["ram"]), range(&part["vram"])); + for i in 0..2 { + ram[i] += r[i]; + vram[i] += v[i]; + } + }; + let model = &e["models"][sel.profile]; + if !model.is_object() { + return Err("Unknown model memory estimate".into()); + } + if sel.download_models { + add(&serde_json::json!({"ram": if gpu.is_some() { &model["hostRam"] } else { &model["cpuRam"] }, "vram": if gpu.is_some() { model["vram"].clone() } else { serde_json::json!([0, 0]) }})); + } + let english = sel.conversation_language == "en"; + if sel.recognition { + add(&e[if english { "recognitionEnglish" } else { "recognitionMultilingual" }]); + } + if sel.router { + add(&e["router"]); + } + match sel.voice_mode { + "qwen" => add(&e["voiceQwenCpu"]), + "" | "off" => {} + _ => add(&e[if english { "voiceEnglish" } else { "voiceMultilingual" }]), + } + let free_vram = gpu.and_then(|g| g.free_vram_mib).map(|m| m as f64 / 1024.0); + let total_vram = gpu.and_then(|g| g.vram_mib).map(|m| m as f64 / 1024.0); + let offload = sel.download_models && gpu.is_some() && vram[1] > free_vram.or(total_vram).unwrap_or(0.0); + if offload { + ram[1] += range(&model["cpuRam"])[1]; + } + let round = |v: f64| (v * 10.0).round() / 10.0; + let row = |r: [f64; 2], total: Option, available: Option| BudgetRow { + estimate: [round(r[0]), round(r[1])], + total, + available, + exceeds_available: available.or(total).is_some_and(|a| r[1] > a), + }; + let gib = |b: u64| b as f64 / (1u64 << 30) as f64; + Ok(MemoryBudget { + gpu_mode: gpu.is_some(), + offload, + ram: row(ram, Some(gib(hw.ram_bytes)), Some(gib(hw.available_ram_bytes))), + vram: row(vram, total_vram, free_vram), + }) +} + +/// `capri-hf-<24 hex>:latest` +pub fn is_hf_alias(model: &str) -> bool { + model.strip_prefix("capri-hf-").and_then(|r| r.strip_suffix(":latest")).is_some_and(|h| h.len() == 24 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())) +} + +/// Managed Qwen alias `capri-qwen3.5:(0.8|2|4|9)b` (context at least 32768). +pub fn is_managed_qwen(model: &str) -> bool { + matches!(model, "capri-qwen3.5:0.8b" | "capri-qwen3.5:2b" | "capri-qwen3.5:4b" | "capri-qwen3.5:9b") +} + +/// Context window choices for a model and its limit. +pub fn context_choices(model: &str, limit: Option) -> Vec { + let small: &[u32] = if is_hf_alias(model) { &[8192, 16384] } else { &[] }; + small.iter().chain(&[32768, 65536, 131072, 262144]).copied().filter(|&c| c <= limit.unwrap_or(262_144)).collect() +} + +/// Local turn output budget: `num_predict` for managed local models, `None` for others. +pub fn output_budget(model: &str, thinking: bool, num_ctx: u32, configured: Option) -> Option { + if !(is_managed_qwen(model) || is_hf_alias(model) || matches!(model, "ministral-3:3b" | "gemma4:e2b")) { + return None; + } + let cap = if thinking { 8192 } else { 2048 }; + Some(cap.min(8192).min(configured.unwrap_or(u32::MAX)).min((num_ctx / 2).max(1))) +} + +/// Writes the settings for a prepared choice. The caller +/// stores both values transactionally (`SettingsStore::update`); models are never deleted. +pub fn apply_choice(settings: &mut Settings, choice: &ModelChoice, cpu_threads: u32) { + let limit = choice.context_limit.unwrap_or(262_144); + let wanted = settings.context_tokens.min(limit); + settings.context_tokens = context_choices(choice.alias, Some(limit)).into_iter().filter(|&c| c <= wanted).max().unwrap_or(8192).max(if is_managed_qwen(choice.alias) { 32768 } else { 0 }); + settings.model = choice.alias.into(); + settings.upstream_model = choice.model.into(); + settings.cpu_threads = Some(cpu_threads); + settings.keep_alive = 300; + let mut inference: InferenceSection = settings.section(); + inference.model_setup_required = false; + inference.preload_models = choice.id == "quality"; + inference.resource_profile = Some(choice.id.into()); + inference.model_capabilities = choice.capabilities.map(|c| c.iter().map(|s| s.to_string()).collect()); + inference.model_context_limit = choice.context_limit; + inference.thinking_default = if choice.capabilities.is_some_and(|c| !c.contains(&"thinking")) { "off" } else { "low" }.into(); + settings.set_section(&inference); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hardware::Gpu; + + fn hw(ram_gib: f64, vram_gib: Option) -> Hardware { + let gpus = vram_gib.map(|v| Gpu { vendor: "nvidia".into(), vram_mib: Some((v * 1024.0) as u64), memory_kind: "dedicated".into(), ..Default::default() }).into_iter().collect(); + Hardware { ram_bytes: (ram_gib * (1u64 << 30) as f64) as u64, available_ram_bytes: 4 << 30, cpu_threads: 20, gpus, ..Default::default() } + } + + #[test] + fn ram_rule_and_requirements() { + for (ram, req, ok) in [(7.5, 8.0, true), (7.4, 8.0, false), (15.0, 16.0, true), (22.5, 24.0, true), (29.9, 32.0, false)] { + assert_eq!(meets_profile_ram(ram, req), ok, "{ram} vs {req}"); + } + let desktop = choice("desktop").unwrap(); + assert_eq!(profile_ram_requirement(desktop, &hw(16.0, Some(7.875))), 12.0); + assert_eq!(profile_ram_requirement(desktop, &hw(16.0, Some(7.8))), 24.0); + assert_eq!(profile_ram_requirement(choice("minimal").unwrap(), &hw(8.0, Some(12.0))), 8.0); + } + + #[test] + fn recommendations_matrix() { + let pick = |ram, vram| recommend_profile(&hw(ram, vram)).profile.map(|p| p.id); + assert_eq!(pick(7.4, None), None); + assert_eq!(pick(8.0, None), Some("minimal")); + assert_eq!(pick(16.0, None), Some("balanced")); + assert_eq!(pick(8.0, Some(4.0)), Some("balanced"), "GPU lowers the RAM requirement"); + assert_eq!(pick(22.9, Some(7.96)), Some("desktop"), "this laptop: 23 GiB RAM, 8 GiB RTX 5070"); + assert_eq!(pick(32.0, Some(12.0)), Some("quality")); + let mut shared = hw(32.0, Some(16.0)); + shared.gpus[0].memory_kind = "shared".into(); + assert_eq!(recommend_profile(&shared).profile.map(|p| p.id), Some("balanced"), "shared memory is never VRAM"); + let r = recommend_profile(&hw(16.0, None)); + assert_eq!(r.reasons[1], "Dedicated VRAM is unknown; a conservative text profile is selected."); + assert_eq!(r.cpu_threads, 4); + assert_eq!(select_model_choice("gemma4-e2b", &hw(16.0, None)).unwrap_err(), "This model needs more system RAM."); + assert_eq!(select_model_choice("quality", &hw(16.0, None)).unwrap_err(), "quality requires at least 32 GiB RAM for the detected GPU/CPU configuration."); + assert_eq!(recommend_models_for_language("en", &hw(22.9, Some(7.96))), ["desktop", "ministral-3-3b"]); + assert!(recommend_models_for_language("xx", &hw(64.0, None)).is_empty()); + } + + #[test] + fn budget_context_and_apply() { + let b = estimate_memory_budget(&Selection { profile: "desktop", download_models: true, conversation_language: "en", router: true, ..Default::default() }, &hw(24.0, Some(8.0))).unwrap(); + assert_eq!(b.ram.estimate, [3.1, 6.5]); + assert_eq!(b.vram.estimate, [4.2, 7.2]); + assert!(!b.offload); + let cpu = estimate_memory_budget(&Selection { profile: "quality", download_models: true, ..Default::default() }, &hw(16.0, None)).unwrap(); + assert_eq!(cpu.ram.estimate, [10.0, 16.0]); + assert!(estimate_memory_budget(&Selection { profile: "nope", ..Default::default() }, &hw(16.0, None)).is_err()); + + assert_eq!(context_choices("gemma4:e2b", Some(131072)), [32768, 65536, 131072]); + assert_eq!(context_choices("capri-hf-0123456789abcdef01234567:latest", Some(16384)), [8192, 16384]); + assert_eq!(output_budget("capri-qwen3.5:4b", false, 32768, None), Some(2048)); + assert_eq!(output_budget("capri-qwen3.5:4b", true, 8192, None), Some(4096)); + assert_eq!(output_budget("vendor/x", true, 8192, None), None); + + let mut s = Settings { context_tokens: 262144, ..Default::default() }; + apply_choice(&mut s, choice("gemma4-e2b").unwrap(), 4); + assert_eq!((s.model.as_str(), s.upstream_model.as_str(), s.context_tokens), ("gemma4:e2b", "gemma4:e2b", 131072)); + let inf: InferenceSection = s.section(); + assert_eq!((inf.resource_profile.as_deref(), inf.thinking_default.as_str(), inf.model_context_limit), (Some("gemma4-e2b"), "low", Some(131072))); + apply_choice(&mut s, choice("ministral-3-3b").unwrap(), 4); + assert_eq!(s.section::().thinking_default, "off"); + } +}