diff --git a/README.md b/README.md index ed5cbc1..91c65e2 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ The main model is **Drama-3-Japanese** (`StudioYebisu-ship-it/Drama-3-Japanese-s - Export: one WAV per line (filename template with serial numbers) / combined WAV (with silence before and after) / SRT / txt - **Model catalog**: download Drama-3-Japanese (Q4_K/Q5_K + sidecar), Irodori-TTS-mf and Qwen3-ASR from inside the app (resumable, SHA-256 checked, license consent, VRAM-based recommendation, profile created automatically). Catalog: `assets/models/catalog.json` - Model profiles: speech.exe (can be downloaded from the official release), GGUF (or a catalog name), device, environment variables; checks for the sidecar and the VRAM needed +- System protection: before a model is loaded, checks that it fits in the free VRAM (or memory) and asks, or refuses at the strictest level (設定 → システム保護) ## Installation diff --git a/docs/deviations.md b/docs/deviations.md index 942b76c..0d439b7 100644 --- a/docs/deviations.md +++ b/docs/deviations.md @@ -427,3 +427,20 @@ Requests: (1) a way to stop playback, (2) choosing a Drama-3 voice by text promp - **Checked**: `src/app/Dialog.test.tsx` and `src/features/models/ModelManager.test.tsx` fail without the fixes and pass with them. In the app (over the WebView2 DevTools protocol, real key and mouse input): Esc closes 書き出し and 設定, and switching between the Drama-3 and Irodori profiles shows each one's own env. - **User impact**: Esc closes the export dialog. Picking a profile on the モデル screen no longer shows, or on leaving the field saves, another profile's environment variables. + +### D-58 System protection: a free-memory check before the engine starts 【追加(ユーザー要望)】 +- **What**: `engine_start` (`commands.rs`, `src-tauri/src/memguard.rs`) checks, before it stops the running worker and starts the new one, that the model will fit in the free memory of the device it loads on. Free memory comes from `speech devices --json` (0.15 s) with the profile's speech.exe; the device is the profile's (`auto`/empty: the first GPU, else the CPU; `gpu`; `cpu`; or a name), so a CPU profile is checked against main memory. The need is estimated from the model file's size: file × 1.1 + 512 MiB (Drama-3 Q4_K: 20.8 GiB file → 23.4 GiB, measured about 23.5 GiB). What the running engine holds on the same device counts as free, since it stops first: it is measured after each start as the free memory before minus after (the estimate until then, or when the figure looks wrong). + - **設定 → システム保護** (`memoryGuard` in settings.json; an unknown value reads as 標準): + - **オフ**: no check. + - **弱**: asks when the model file alone is larger than the free memory. + - **標準** (default): asks when the estimate is larger than the free memory. + - **強**: does not start unless the estimate plus 1.5 GiB (for the desktop and other programs) is free. + - "Asks" is a `confirm()` with the device, the need and the free memory; on yes the UI calls `engine_start` again with `confirmed`. 強 returns `blocked` whatever `confirmed` says, and the UI shows a notice pointing to the setting. `engine_start` now returns `{status: "started" | "confirm" | "blocked", check}`. + - The モデル screen's "必要VRAM 目安" uses the same estimate (it was file × 1.1). +- **Why**: The user asked to keep a model from being loaded over VRAM another program is using, which can freeze the PC, without refusing loads that would fit; hence an estimate close to the measured figure, a confirmation instead of a refusal below 強, and a setting for the strength. +- **Not done / limits**: + - The estimate is from the file size only. Drama-3 with `experts_on_cpu` (on by default) may still run when the estimate does not fit, by computing some experts on the CPU; 標準 then asks, and yes starts it as before. The context length and other options are not taken into account. + - The check is skipped, and the engine starts, when `speech devices` fails, the device is not listed or the model file cannot be read. + - Memory another program takes after the check is not seen. With the check off, nothing is measured, so after turning it on, the running engine's memory counts as used until the next start. + - Not tried against a GPU that is really short of memory: the judgement is covered by unit tests (`memguard.rs`, `src/store/app.test.ts`). +- **User impact**: Starting or switching a model when the device looks short of memory asks first (標準), or is refused (強). A start that fits is unchanged apart from the extra 0.15 s `speech devices` call. diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 1e8aa08..cb75c89 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -11,6 +11,7 @@ use tauri::{AppHandle, Manager, State}; use crate::audio::{self, Cue, ExportItem}; use crate::engine::{EngineState, EngineSupervisor}; use crate::jobs::{GenerationQueue, JobSpec, QueueSnapshot}; +use crate::memguard::{self, GuardLevel, Held, MemoryCheck, Verdict}; use crate::models::{adapter_for, all_adapters, describe, AdapterDescriptor, VoiceInput}; use crate::project::{self, Project}; use crate::settings::{AppSettings, ModelProfile}; @@ -27,6 +28,8 @@ pub struct AppState { pub downloads: crate::downloads::Downloads, /// A catalog.json here replaces the built-in model catalog. pub catalog_override: PathBuf, + /// What the running engine holds on its device, to count as free when another start stops it (D-58). + pub engine_memory: Arc>>, } type R = Result; @@ -120,14 +123,77 @@ pub fn engine_state(st: State<'_, AppState>) -> EngineState { st.supervisor.state() } +/// What `engine_start` did: started, or held back by the memory check (D-58). +#[derive(Serialize)] +#[serde(tag = "status", rename_all = "camelCase")] +pub enum StartResult { + Started, + /// Not started: asks the user first. `engine_start` again with `confirmed` starts it. + Confirm { + check: MemoryCheck, + }, + /// Not started, and `confirmed` does not change that. + Blocked { + check: MemoryCheck, + }, +} + +/// The free-memory check for loading `model_path` with `p`, or `None` when it is off or cannot be +/// made (devices not listed, device or file unknown): then the engine starts as before. +async fn memory_check(st: &AppState, p: &ModelProfile, model_path: &str, level: GuardLevel) -> Option { + if level == GuardLevel::Off { + return None; + } + let file_bytes = std::fs::metadata(model_path).ok()?.len(); + let devices = Speech { exe: &p.speech_exe, env: &p.env }.devices().await.ok()?; + let dev = memguard::pick_device(&devices, &p.device)?; + // The running engine stops before the new one loads, so what it holds there counts as free. + let reclaim = match (st.supervisor.live(), st.engine_memory.lock().unwrap().as_ref()) { + (Ok(_), Some(h)) if h.device == dev.name => h.bytes, + _ => 0, + }; + memguard::check(level, &dev, reclaim, file_bytes) +} + #[tauri::command] -pub async fn engine_start(st: State<'_, AppState>, profile_id: String) -> R<()> { +pub async fn engine_start(st: State<'_, AppState>, profile_id: String, confirmed: Option) -> R { let p = st.profile(&profile_id)?; if p.model.trim().is_empty() { return Err("モデル (GGUF) のパスが設定されていません".into()); } let path = Speech { exe: &p.speech_exe, env: &p.env }.resolve_model(&p.model).await.map_err(e)?; - st.supervisor.start(&p, path).await.map_err(e) + let level = st.settings.lock().unwrap().memory_guard; + let check = memory_check(&st, &p, &path, level).await; + match &check { + Some(c) if c.verdict == Verdict::Block => return Ok(StartResult::Blocked { check: c.clone() }), + Some(c) if c.verdict == Verdict::Confirm && confirmed != Some(true) => { + return Ok(StartResult::Confirm { check: c.clone() }) + } + _ => {} + } + *st.engine_memory.lock().unwrap() = None; + st.supervisor.start(&p, path).await.map_err(e)?; + if let Some(c) = check { + // Until it is measured, the engine is taken to hold the estimate. + let held = st.engine_memory.clone(); + let bytes = memguard::estimate(c.file_bytes); + *held.lock().unwrap() = Some(Held { profile_id: p.id.clone(), device: c.device.clone(), bytes }); + // Measure what loading took: free before (without what the old engine freed) minus free now. + let before = c.free - c.reclaim; + tokio::spawn(async move { + let devices = Speech { exe: &p.speech_exe, env: &p.env }.devices().await.ok(); + let Some(now) = devices.and_then(|d| memguard::pick_device(&d, &c.device)) else { return }; + let used = before.saturating_sub(now.free); + let mut g = held.lock().unwrap(); + // Only for this start, and only a plausible figure (another program may have freed memory meanwhile). + if let Some(h) = g.as_mut().filter(|h| h.profile_id == p.id && h.device == c.device) { + if used > bytes / 4 { + h.bytes = used; + } + } + }); + } + Ok(StartResult::Started) } #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b072f6a..2b4c72e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -7,6 +7,7 @@ pub mod engine; pub mod events; pub mod installer; pub mod jobs; +pub mod memguard; mod memory; pub mod models; pub mod project; @@ -98,6 +99,7 @@ pub fn run() { work, downloads: Default::default(), catalog_override: cfg.join("catalog.json"), + engine_memory: Default::default(), }); Ok(()) }) diff --git a/src-tauri/src/memguard.rs b/src-tauri/src/memguard.rs new file mode 100644 index 0000000..95e72e0 --- /dev/null +++ b/src-tauri/src/memguard.rs @@ -0,0 +1,239 @@ +//! System protection: before the engine starts, checks that the model will fit in the free memory +//! of the device it is loaded on, so that loading it over a GPU another program is using does not +//! push Windows into paging VRAM and freeze the PC (D-58). +//! +//! The check is deliberately not strict by default: a shortfall only asks the user, except at +//! `Strict`, and anything it cannot measure (an older speech.exe, an unknown device) lets the +//! engine start. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +const MIB: u64 = 1 << 20; +const GIB: u64 = 1 << 30; +/// Buffers beside the weights (codec, KV cache, compute): Drama-3 Q4_K's 20.8 GiB file takes +/// about 23.5 GiB of VRAM, and file × 1.1 + 512 MiB comes to 23.4 GiB. +const WORK_FIXED: u64 = 512 * MIB; +/// What `Strict` leaves free for the desktop and other programs on top of the estimate. +pub const STRICT_RESERVE: u64 = 3 * GIB / 2; + +/// How hard the check guards the system. +#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub enum GuardLevel { + /// No check. + Off, + /// Asks only when the model file itself is larger than the free memory. + Low, + /// Asks when the estimate (file and working buffers) is larger than the free memory. + /// Also what an unknown value in settings.json reads as. + #[default] + Standard, + /// Refuses to start unless the estimate plus `STRICT_RESERVE` is free. + Strict, +} + +impl<'de> Deserialize<'de> for GuardLevel { + fn deserialize>(d: D) -> Result { + // An unknown value must not make the whole settings.json unreadable. + Ok(match Value::deserialize(d)?.as_str() { + Some("off") => GuardLevel::Off, + Some("low") => GuardLevel::Low, + Some("strict") => GuardLevel::Strict, + _ => GuardLevel::Standard, + }) + } +} + +#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Verdict { + Fits, + /// Start only if the user confirms. + Confirm, + /// Do not start. + Block, +} + +/// One entry of `speech devices --json`. +#[derive(Debug, Clone, PartialEq)] +pub struct DeviceMemory { + pub name: String, + pub description: String, + pub gpu: bool, + pub free: u64, + pub total: u64, +} + +/// The device `speech worker --device NAME` loads on: `auto`/empty is the first GPU (the CPU +/// without one), `gpu` the first GPU, `cpu` the CPU, anything else a device name. +pub fn pick_device(devices: &Value, wanted: &str) -> Option { + let list: Vec = devices + .get("devices")? + .as_array()? + .iter() + .filter_map(|d| { + Some(DeviceMemory { + name: d.get("name")?.as_str()?.to_string(), + description: d.get("description").and_then(Value::as_str).unwrap_or("").trim().to_string(), + gpu: d.get("kind").and_then(Value::as_str) == Some("gpu"), + free: d.get("memory_free")?.as_u64()?, + total: d.get("memory_total").and_then(Value::as_u64).unwrap_or(0), + }) + }) + .collect(); + let w = wanted.trim().to_ascii_lowercase(); + let found = match w.as_str() { + "" | "auto" => list.iter().find(|d| d.gpu).or_else(|| list.iter().find(|d| !d.gpu)), + "gpu" => list.iter().find(|d| d.gpu), + "cpu" => list.iter().find(|d| !d.gpu), + _ => list.iter().find(|d| d.name.eq_ignore_ascii_case(&w)), + }; + found.cloned() +} + +/// Memory a model of `file_bytes` takes once loaded, weights and working buffers. +pub fn estimate(file_bytes: u64) -> u64 { + file_bytes + file_bytes / 10 + WORK_FIXED +} + +/// The result of a check, shown to the user when it does not fit. +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct MemoryCheck { + pub level: GuardLevel, + pub device: String, + pub description: String, + pub gpu: bool, + /// Free now, plus what the running engine frees on this device when it stops. + pub free: u64, + /// Of `free`, what the running engine holds. + pub reclaim: u64, + pub total: u64, + pub file_bytes: u64, + /// What the level asks to be free. + pub need: u64, + pub verdict: Verdict, +} + +/// Judges a model of `file_bytes` against `dev`, counting `reclaim` (held by the engine that +/// stops first) as free. `None` at `Off`. +pub fn check(level: GuardLevel, dev: &DeviceMemory, reclaim: u64, file_bytes: u64) -> Option { + let (need, short) = match level { + GuardLevel::Off => return None, + GuardLevel::Low => (file_bytes, Verdict::Confirm), + GuardLevel::Standard => (estimate(file_bytes), Verdict::Confirm), + GuardLevel::Strict => (estimate(file_bytes) + STRICT_RESERVE, Verdict::Block), + }; + // Never more than the device has: a stale measurement must not inflate it. + let free = (dev.free + reclaim).min(if dev.total > 0 { dev.total } else { u64::MAX }); + Some(MemoryCheck { + level, + device: dev.name.clone(), + description: dev.description.clone(), + gpu: dev.gpu, + free, + reclaim, + total: dev.total, + file_bytes, + need, + verdict: if free >= need { Verdict::Fits } else { short }, + }) +} + +/// Memory the running engine was measured (or estimated) to hold, to count it as free when +/// another start stops it first. +#[derive(Debug, Clone, PartialEq)] +pub struct Held { + pub profile_id: String, + pub device: String, + pub bytes: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn devices() -> Value { + json!({"devices": [ + {"name": "Vulkan0", "description": "NVIDIA GeForce RTX 5090", "kind": "gpu", + "memory_total": 33_750_515_712u64, "memory_free": 32_945_209_344u64}, + {"name": "CPU", "description": "AMD Ryzen 7 9800X3D ", "kind": "cpu", + "memory_total": 68_293_152_768u64, "memory_free": 30_593_986_560u64}, + ]}) + } + + fn gpu(free_gib: f64) -> DeviceMemory { + DeviceMemory { + name: "Vulkan0".into(), + description: String::new(), + gpu: true, + free: (free_gib * GIB as f64) as u64, + total: 32 * GIB, + } + } + + const DRAMA_Q4K: u64 = 22_359_473_504; + + #[test] + fn picks_the_device_the_worker_uses() { + let d = devices(); + assert_eq!(pick_device(&d, "Vulkan0").unwrap().free, 32_945_209_344); + assert_eq!(pick_device(&d, "vulkan0").unwrap().name, "Vulkan0"); + assert_eq!(pick_device(&d, "auto").unwrap().name, "Vulkan0"); + assert_eq!(pick_device(&d, "").unwrap().name, "Vulkan0"); + assert_eq!(pick_device(&d, "gpu").unwrap().name, "Vulkan0"); + let cpu = pick_device(&d, "CPU").unwrap(); + assert!(!cpu.gpu); + assert_eq!(cpu.description, "AMD Ryzen 7 9800X3D"); + assert_eq!(pick_device(&d, "Vulkan1"), None); + let cpu_only = json!({"devices": [{"name": "CPU", "kind": "cpu", "memory_free": 5, "memory_total": 9}]}); + assert_eq!(pick_device(&cpu_only, "auto").unwrap().name, "CPU"); + assert_eq!(pick_device(&cpu_only, "gpu"), None); + assert_eq!(pick_device(&json!({"error": "x"}), "auto"), None); + } + + #[test] + fn the_estimate_matches_the_measured_drama_vram() { + // Measured: about 23.5 GiB above idle (docs/engine-protocol.md). + let est = estimate(DRAMA_Q4K) as f64 / GIB as f64; + assert!((23.0..24.0).contains(&est), "{est}"); + } + + #[test] + fn levels_get_stricter_in_order() { + // Drama-3 Q4_K (20.8 GiB file, 23.4 GiB estimate) on a GPU with this much free: + let v = |level, free| check(level, &gpu(free), 0, DRAMA_Q4K).map(|c| c.verdict); + assert_eq!(v(GuardLevel::Off, 1.0), None); + // Plenty free: nothing asks. + for l in [GuardLevel::Low, GuardLevel::Standard, GuardLevel::Strict] { + assert_eq!(v(l, 26.0), Some(Verdict::Fits)); + } + // 24 GiB free: fits the estimate, but not with the strict reserve. + assert_eq!(v(GuardLevel::Standard, 24.0), Some(Verdict::Fits)); + assert_eq!(v(GuardLevel::Strict, 24.0), Some(Verdict::Block)); + // 22 GiB free: the file fits, the estimate does not. + assert_eq!(v(GuardLevel::Low, 22.0), Some(Verdict::Fits)); + assert_eq!(v(GuardLevel::Standard, 22.0), Some(Verdict::Confirm)); + // 12 GiB free: even the file does not fit. + assert_eq!(v(GuardLevel::Low, 12.0), Some(Verdict::Confirm)); + } + + #[test] + fn the_running_engine_counts_as_free_up_to_the_total() { + let c = check(GuardLevel::Standard, &gpu(6.0), 24 * GIB, DRAMA_Q4K).unwrap(); + assert_eq!(c.verdict, Verdict::Fits); + assert_eq!(c.free, 30 * GIB); + let c = check(GuardLevel::Standard, &gpu(20.0), 24 * GIB, DRAMA_Q4K).unwrap(); + assert_eq!(c.free, 32 * GIB); + } + + #[test] + fn levels_serialize_as_the_settings_store_them() { + assert_eq!(serde_json::to_value(GuardLevel::Standard).unwrap(), json!("standard")); + assert_eq!(serde_json::from_value::(json!("strict")).unwrap(), GuardLevel::Strict); + assert_eq!(serde_json::from_value::(json!("paranoid")).unwrap(), GuardLevel::Standard); + assert_eq!(GuardLevel::default(), GuardLevel::Standard); + } +} diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 2f76d79..d353d9b 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -5,6 +5,7 @@ use std::path::Path; use serde::{Deserialize, Serialize}; +use crate::memguard::GuardLevel; use crate::models::adapter_for; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -71,6 +72,8 @@ pub struct AppSettings { /// Playback volume, 0.0 to 2.0 (200%), as the slider shows it (the GUI applies a loudness curve). pub playback_volume: f64, pub playback_muted: bool, + /// System protection: how hard the free-memory check before an engine start is (D-58). + pub memory_guard: GuardLevel, } impl Default for AppSettings { @@ -88,6 +91,7 @@ impl Default for AppSettings { recent_projects: Vec::new(), playback_volume: 1.0, playback_muted: false, + memory_guard: GuardLevel::default(), } } } @@ -160,5 +164,6 @@ mod tests { assert_eq!(partial.asr_model, "qwen3-asr-0.6b"); assert_eq!(partial.playback_volume, 1.0); assert!(!partial.playback_muted); + assert_eq!(partial.memory_guard, GuardLevel::Standard); } } diff --git a/src/app/Rail.test.tsx b/src/app/Rail.test.tsx index 0d1a8ba..5c71500 100644 --- a/src/app/Rail.test.tsx +++ b/src/app/Rail.test.tsx @@ -28,6 +28,7 @@ const settings = (active: string, p1Model = "/m.gguf"): AppSettings => ({ recentProjects: [], playbackVolume: 1, playbackMuted: false, + memoryGuard: "standard", }); const startEngine = vi.fn(async () => {}); diff --git a/src/app/StatusBar.test.tsx b/src/app/StatusBar.test.tsx index 2099629..760dc31 100644 --- a/src/app/StatusBar.test.tsx +++ b/src/app/StatusBar.test.tsx @@ -30,6 +30,7 @@ const settings: AppSettings = { recentProjects: [], playbackVolume: 1, playbackMuted: false, + memoryGuard: "standard", }; describe("formatEta", () => { diff --git a/src/app/TopBar.test.tsx b/src/app/TopBar.test.tsx index 3ad1527..ad367dd 100644 --- a/src/app/TopBar.test.tsx +++ b/src/app/TopBar.test.tsx @@ -83,6 +83,7 @@ describe("TopBar", () => { recentProjects: [], playbackVolume: 0.8, playbackMuted: false, + memoryGuard: "standard", } as unknown as AppSettings; const st = () => useApp.getState().settings!; diff --git a/src/features/models/ModelManager.test.tsx b/src/features/models/ModelManager.test.tsx index 9a88093..4bf8dc5 100644 --- a/src/features/models/ModelManager.test.tsx +++ b/src/features/models/ModelManager.test.tsx @@ -36,6 +36,7 @@ const settings: AppSettings = { recentProjects: [], playbackVolume: 1, playbackMuted: false, + memoryGuard: "standard", }; const adapter: AdapterDescriptor = { id: "irodori", diff --git a/src/features/models/ModelManager.tsx b/src/features/models/ModelManager.tsx index 070165e..b24978b 100644 --- a/src/features/models/ModelManager.tsx +++ b/src/features/models/ModelManager.tsx @@ -78,6 +78,8 @@ export function ModelManager() { const running = engine.state !== "stopped" && "profileId" in engine && engine.profileId === sel; const free = devices.find((d) => d.name === prof?.device)?.memory_free; const need = check && typeof check !== "string" ? Number(check.info.file_bytes ?? 0) : 0; + // The same estimate as the check before an engine start (memguard::estimate, D-58). + const est = need * 1.1 + 512 * 2 ** 20; return ( @@ -280,9 +282,9 @@ export function ModelManager() { )} {need > 0 && free !== undefined && ( -
need * 1.1 ? "ok-text" : "warn-text"}> - 必要VRAM 目安 {gib(need * 1.1)}(ファイル {gib(need)} + 作業領域) / 空き {gib(free)} - {free <= need * 1.1 && " — 一部のエキスパートが CPU で計算され遅くなります"} +
est ? "ok-text" : "warn-text"}> + 必要VRAM 目安 {gib(est)}(ファイル {gib(need)} + 作業領域) / 空き {gib(free)} + {free <= est && " — 一部のエキスパートが CPU で計算され遅くなります"}
)}
diff --git a/src/features/settings/SettingsDialog.tsx b/src/features/settings/SettingsDialog.tsx index f9991b8..5c0456d 100644 --- a/src/features/settings/SettingsDialog.tsx +++ b/src/features/settings/SettingsDialog.tsx @@ -3,6 +3,7 @@ import { ipc } from "../../lib/ipc"; import { useApp } from "../../store/app"; import { Dialog } from "../../app/Dialog"; import { InstallButton } from "../models/ModelManager"; +import type { MemoryGuard } from "../../lib/types"; export function SettingsDialog() { const s = useApp((x) => x.settings)!; @@ -34,6 +35,22 @@ export function SettingsDialog() { + +

+ ほかのアプリが VRAM を使っているところへモデルを読み込んで PC + が固まるのを防ぎます。必要量はモデルファイルの大きさからの推定で、実際には載ることもあります。弱・標準では足りないときも確認のうえ起動でき、強では起動しません。 +