use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::time::Instant; use color_eyre::eyre::{Result, WrapErr, eyre}; use transcribe_cpp::{Backend, Model, ModelOptions, RunOptions, TimestampKind}; use crate::app_settings::TranscriptionDevice; use crate::transcription::gguf_session::{OfflineGgufSession, output_truncated}; use crate::transcription::gpu_health; use crate::transcription::models::{ TranscriptionModelId, TranscriptionSelection, download_with_progress, model_path, validate, }; use crate::transcription::{pad_gguf_samples, requires_closing_mark, trailing_silence_samples}; /// A word or segment's start and end (ms from the clip's start) and text. pub type TimedSpan = (i64, i64, String); pub struct LocalTranscriber { session: OfflineGgufSession, selection: TranscriptionSelection, options: RunOptions, device_label: String, max_audio_samples: Option, /// The finest timestamps the model gives, for a capture's or a /// meeting's word times. finest_timestamps: TimestampKind, /// The GPU it runs on; `None` on the CPU. gpu: Option, /// The device setting it loaded for. preference: TranscriptionDevice, /// A warm run of [`PREWARM_SAMPLES`] once loaded, in milliseconds. warm_ms: u128, /// It loaded on the CPU because the GPU ran out of memory, as it does /// when another copy of a model already fills it (#1170). gpu_full: bool, /// The GPU out-of-memory fallback it took mid-run, for the dictation /// engine to publish in Settings (#1984). Not saved. out_of_memory: Option, } /// 1.5 s of silence: what loading runs to warm a model and time it. const PREWARM_SAMPLES: usize = 24_000; /// An integrated GPU slower than this on a warm 1.5 s run (a fifth of real /// time) may lose to the CPU, so Auto times the CPU too (#484). Healthy /// GPUs run it in tens of milliseconds; the UHD 620 and Iris Plus 655 that /// missed streaming deadlines ran a 35 s clip at about 0.4× real time. const SLOW_WARM_MS: u128 = 300; /// Settings › Speech engine (`transcription_device`), for every later load. static DEVICE: AtomicU8 = AtomicU8::new(0); pub(crate) fn set_device(device: TranscriptionDevice) { DEVICE.store(device as u8, Ordering::Relaxed); } pub(crate) fn device() -> TranscriptionDevice { match DEVICE.load(Ordering::Relaxed) { 1 => TranscriptionDevice::Gpu, 2 => TranscriptionDevice::Cpu, _ => TranscriptionDevice::Auto, } } pub fn install(selection: &TranscriptionSelection, canceled: &AtomicBool) -> Result<()> { let model = validate(selection)?; let downloaded = AtomicU64::new(0); println!("Installing {} ({})...", model.name, model.size_label()); let path = download_with_progress(model, canceled, &downloaded)?; println!( "Installed {} bytes at {}", downloaded.load(Ordering::Relaxed), path.display() ); Ok(()) } /// Speech engine was CPU when [`init_backends`] ran, so only the CPU /// backend registered. static CPU_CHOSEN: AtomicBool = AtomicBool::new(false); /// Registers transcribe.cpp's backends once per process and returns the /// backend models load on: every GPU (`Auto`), or only the CPU when Speech /// engine is CPU, so no GPU driver loads (#1253), or on Windows after a /// launch of this build crashed while ggml started a GPU (#662). A GPU /// driver crash can't be caught, so a marker file spans that work. pub fn init_backends() -> Result { static BACKEND: std::sync::OnceLock = std::sync::OnceLock::new(); if let Some(backend) = BACKEND.get() { return Ok(*backend); } transcribe_cpp::init_logging(); let cpu_only = || { transcribe_cpp::init_backends_with( None::<&Path>, transcribe_cpp::BackendMask::for_backend(Backend::Cpu), ) .wrap_err("could not initialize the CPU transcription backend") }; #[cfg(target_os = "windows")] if gpu_guard::crashed_before() { tracing::warn!( marker = %gpu_guard::marker().map(|path| path.display().to_string()).unwrap_or_default(), "a previous launch of this Hex crashed while starting the GPU for transcription; transcribing on the CPU until Hex updates or the marker is deleted" ); cpu_only()?; return Ok(*BACKEND.get_or_init(|| Backend::Cpu)); } if device() == TranscriptionDevice::Cpu { cpu_only()?; CPU_CHOSEN.store(true, Ordering::Relaxed); return Ok(*BACKEND.get_or_init(|| Backend::Cpu)); } let init = || { transcribe_cpp::init_backends_default()?; // Enumerating the devices makes sure every backend started now. drop(transcribe_cpp::devices()); Ok::<_, transcribe_cpp::Error>(()) }; #[cfg(target_os = "windows")] let init = || gpu_guard::guarded(init); init().wrap_err("could not initialize transcription backends")?; Ok(*BACKEND.get_or_init(|| Backend::Auto)) } /// Speech engine left CPU after this launch registered the CPU alone: the /// GPU needs a restart. pub(crate) fn gpu_after_restart() -> bool { CPU_CHOSEN.load(Ordering::Relaxed) && device() != TranscriptionDevice::Cpu } /// The marker a Windows launch keeps while ggml starts a GPU (`init_backends`, /// a model's load and prewarm). Left behind, that launch crashed in a GPU /// driver; it holds the build's version, so an update tries the GPU again. #[cfg(target_os = "windows")] mod gpu_guard { use std::path::PathBuf; pub(super) fn marker() -> Option { crate::app_paths::support_dir() .ok() .map(|dir| dir.join("gpu-start.pending")) } pub(super) fn crashed_before() -> bool { let Some(path) = marker() else { return false; }; match std::fs::read_to_string(&path) { Ok(version) if version == crate::VERSION => true, Ok(_) => { let _ = std::fs::remove_file(&path); false } Err(_) => false, } } pub(super) fn guarded(work: impl FnOnce() -> T) -> T { let path = marker(); if let Some(path) = &path { if let Some(dir) = path.parent() { let _ = std::fs::create_dir_all(dir); } if let Err(error) = std::fs::write(path, crate::VERSION) { tracing::warn!(%error, "could not write the GPU start marker"); } } let out = work(); if let Some(path) = &path { let _ = std::fs::remove_file(path); } out } } pub fn devices() -> Result> { init_backends()?; Ok(transcribe_cpp::devices() .into_iter() .map(|device| { format!( "{}\t{}\t{} MB\t{}", device .index .map_or_else(|| "-".into(), |index| index.to_string()), device.kind, device.memory_total / (1024 * 1024), if device.description.is_empty() { device.name } else { device.description } ) }) .collect()) } /// Initializes transcribe.cpp's backends, which creates its Vulkan instance, /// on the calling thread. The Linux process calls this before its listener /// or window can start: two Vulkan instances created at once in one process /// (ggml's here, wgpu's for the window) crash inside the Vulkan loader. /// Later model loads reuse the instance. #[cfg(target_os = "linux")] pub fn initialize_backends() { if let Err(error) = init_backends() { tracing::warn!(%error, "could not initialize transcription backends"); } } pub fn transcribe_wav_with_selection( path: &Path, selection: &TranscriptionSelection, ) -> Result { let samples = read_wav_for_parakeet(path)?; LocalTranscriber::load(selection)?.transcribe(&samples) } pub fn read_wav_for_parakeet(path: &Path) -> Result> { let file = std::fs::File::open(path).wrap_err_with(|| format!("could not open {}", path.display()))?; read_wav(std::io::BufReader::new(file)) } fn read_wav(reader: impl std::io::Read + std::io::Seek) -> Result> { let mut reader = hound::WavReader::new(reader)?; let spec = reader.spec(); let samples = match spec.sample_format { hound::SampleFormat::Float => reader .samples::() .collect::, _>>()?, hound::SampleFormat::Int if spec.bits_per_sample <= 16 => reader .samples::() .map(|sample| sample.map(|sample| sample as f32 / i16::MAX as f32)) .collect::, _>>()?, hound::SampleFormat::Int => reader .samples::() .map(|sample| sample.map(|sample| sample as f32 / i32::MAX as f32)) .collect::, _>>()?, }; let channels = usize::from(spec.channels); let mono = samples .chunks(channels) .map(|frame| frame.iter().sum::() / channels as f32) .collect::>(); let mut samples = crate::dictation::resample_for_parakeet(&mono, spec.sample_rate); crate::dictation::pad_for_parakeet(&mut samples); Ok(samples) } impl LocalTranscriber { /// Loads and prewarms `selection` where Settings › Speech engine says: /// on Auto a GPU unless it failed before under its current driver /// ([`gpu_health`], #856), on GPU the best GPU, on CPU the CPU. A GPU load /// or prewarm that fails retries on the CPU, and when the CPU works the /// GPU is remembered as failed. pub fn load(selection: &TranscriptionSelection) -> Result { let loaded = Self::load_where(selection)?; gpu_health::set_auto_on_cpu( loaded.preference == TranscriptionDevice::Auto && loaded.gpu.is_none(), ); Ok(loaded) } fn load_where(selection: &TranscriptionSelection) -> Result { let backend = init_backends()?; let preference = device(); if backend == Backend::Cpu || preference == TranscriptionDevice::Cpu { return Self::load_on(selection, Backend::Cpu, None, preference); } let gpus = gpu_health::gpus(); let (backend, target) = if preference == TranscriptionDevice::Gpu || !gpus.iter().any(gpu_health::failed) { (Backend::Auto, None) } else { let healthy = gpus .iter() .find(|gpu| !gpu_health::failed(gpu) && gpu_health::backend(gpu).is_some()); match healthy.and_then(|gpu| Some((gpu_health::backend(gpu)?, gpu.clone()))) { Some((backend, gpu)) => (backend, Some(gpu)), None => { tracing::info!( "this GPU failed or ran slower than the CPU before, under its current driver; transcribing on the CPU (Settings › Speech engine › GPU tries it again)" ); return Self::load_on(selection, Backend::Cpu, None, preference); } } }; // The GPU this load runs on: the one chosen, else the one Auto picks. let expected = target.clone().or_else(|| gpus.into_iter().next()); let on_gpu = || Self::load_on(selection, backend, target, preference); #[cfg(target_os = "windows")] let on_gpu = || gpu_guard::guarded(on_gpu); match on_gpu() { Ok(loaded) => { if preference == TranscriptionDevice::Gpu && let Some(gpu) = &loaded.gpu { gpu_health::forget(gpu); } if preference == TranscriptionDevice::Auto && loaded.slow_igpu() { return Ok(loaded.or_faster_cpu()); } Ok(loaded) } Err(error) => { tracing::warn!( error = format!("{error:#}"), "could not load the transcription model on the GPU; loading it on the CPU" ); let mut loaded = Self::load_on(selection, Backend::Cpu, None, preference)?; // The CPU loads the same model, so the GPU failed, unless it // only ran out of memory (another copy can fill it, #1165). if let Some(gpu) = &expected { if gpu_health::out_of_memory(&error) { tracing::info!( "the GPU ran out of memory; not remembering it as failed, Auto tries it again next load" ); loaded.gpu_full = true; } else { gpu_health::record(gpu, &format!("{error:#}")); } } Ok(loaded) } } } fn load_on( selection: &TranscriptionSelection, backend: Backend, target: Option, preference: TranscriptionDevice, ) -> Result { let definition = validate(selection)?; if !crate::transcription::models::is_installed(definition, &selection.language) { return Err(eyre!( "{} is not installed; run `cargo run -- model install`", definition.name )); } let path = model_path(definition)?; let model = Model::load_with( &path, &ModelOptions { backend, device: target, ..Default::default() }, ) .wrap_err_with(|| format!("could not load transcription model from {}", path.display()))?; let device = model.device()?; let variant = model.variant(); let architecture = model.arch(); let capabilities = model.capabilities()?; let language = crate::transcription::gguf_session::validate_gguf_artifact( &path, definition, &architecture, &variant, selection, capabilities.supports_language_detect, )?; let options = RunOptions { timestamps: if capabilities.max_timestamp_kind == TimestampKind::None { TimestampKind::None } else { TimestampKind::Segment }, language, ..Default::default() }; let device_label = format!("{} ({})", device.description, device.kind); tracing::info!( backend = device.kind, device = device.description, key = gpu_health::device_key(&device), driver = gpu_health::driver(), variant, "loaded local transcription model" ); let session = OfflineGgufSession::new(model)?; let mut transcriber = Self { session, selection: selection.clone(), options, device_label, max_audio_samples: crate::transcription::models::max_audio_chunk_samples( &architecture, capabilities.max_audio_ms, ), finest_timestamps: match capabilities.max_timestamp_kind { TimestampKind::Word | TimestampKind::Token => TimestampKind::Word, kind => kind, }, gpu: matches!( device.device_type, transcribe_cpp::DeviceType::Gpu | transcribe_cpp::DeviceType::Igpu ) .then(|| device.clone()), preference, warm_ms: 0, gpu_full: false, out_of_memory: None, }; let started = Instant::now(); transcriber.warm_on_silence()?; tracing::info!( prewarm_ms = started.elapsed().as_millis(), "prewarmed local transcription model" ); transcriber .session .probe_stream(&transcriber.options, &path); // Warm now, so this times the device rather than its first run's // shader compiles. let started = Instant::now(); transcriber.warm_on_silence()?; transcriber.warm_ms = started.elapsed().as_millis(); Ok(transcriber) } /// Runs [`PREWARM_SAMPLES`] of silence through the model, without the /// vocabulary prompt: with it, a decoder such as Qwen3-ASR reads a long /// term list back to its output cap on every warm-up (#1568). A decode /// that still runs to that cap ran the whole graph on the device, so /// that is a warm model, not a failed device. fn warm_on_silence(&mut self) -> Result<()> { let run = |this: &mut Self| { this.session .warm(&vec![0.0; PREWARM_SAMPLES], &this.options) .map(drop) .wrap_err("transcription failed") }; let result = match run(self) { // A GPU that fails mid-run reloads on the CPU, as a transcript // does; the CPU model is warmed by its own load. Err(error) if self.gpu_failed(&error) => self.recover_on_cpu(&error), result => result, }; match result { Err(error) if output_truncated(&error) => { tracing::info!( error = format!("{error:#}"), "the warm-up run on silence hit the output limit; the model is warm" ); Ok(()) } result => result, } } pub(crate) fn stream_options(&self) -> Option<&transcribe_cpp::StreamOptions> { self.session.stream_options() } /// Re-probes the live stream when Labs › Faster live text or an env /// override changed, so the next capture streams with it. pub(crate) fn refresh_stream(&mut self) { self.session.refresh_stream(&self.options); } /// Silence a live stream of this model hears before it finalizes, the /// same trailing silence its whole-clip runs get. pub(crate) fn stream_trailing_silence(&self) -> usize { trailing_silence_samples(Some(self.model_id())) } /// Whether a live stream of this model must end its text with closing /// sentence punctuation before it is trusted, as Unified English's does /// (issue 1933). pub(crate) fn stream_requires_closing_mark(&self) -> bool { requires_closing_mark(Some(self.model_id())) } /// The model this transcriber was loaded for. pub(crate) fn model_id(&self) -> TranscriptionModelId { self.selection.model } pub(crate) fn with_stream( &mut self, stream_options: &transcribe_cpp::StreamOptions, cancel: &transcribe_cpp::CancelToken, drive: impl FnOnce(&mut transcribe_cpp::Stream<'_>) -> R, ) -> transcribe_cpp::Result { self.session .with_stream(&self.options, stream_options, cancel, drive) } /// The selection this model was loaded for, so the transcription engine /// can say which model it holds. pub(crate) fn gguf_selection(&self) -> Option<&TranscriptionSelection> { Some(&self.selection) } pub(crate) fn matches_selection(&self, selection: &TranscriptionSelection) -> bool { &self.selection == selection } /// The out-of-memory fallback this model took, for the dictation engine /// to publish in Settings (#1984). `None` on a GPU. pub(crate) fn out_of_memory(&self) -> Option<&gpu_health::Failure> { self.out_of_memory.as_ref() } /// Brings an idle model's weights back before audio arrives, as loading /// does; a model that ran recently is already warm. pub(crate) fn prewarm(&mut self) -> Result<()> { if self.session.ran_recently() { return Ok(()); } self.warm_on_silence() .wrap_err("could not prewarm transcription model") } /// Transcribes a complete 16 kHz clip, padded as a dictation's clip is: /// the minimum duration, then Unified English's trailing silence. pub(crate) fn transcribe_clip(&mut self, mut samples: Vec) -> Result { pad_gguf_samples(&mut samples, Some(self.model_id())); self.transcribe(&samples) } /// [`Self::transcribe_clip`] with the model's own segment and word times, /// chunked and padded exactly as the untimed run chunks and pads it, so /// the text matches and each chunk's times sit on the clip's timeline. pub(crate) fn transcribe_timed( &mut self, mut samples: Vec, ) -> Result { pad_gguf_samples(&mut samples, Some(self.model_id())); let options = RunOptions { timestamps: self.finest_timestamps, ..self.options.clone() }; match self .session .transcribe_chunked_timed(&samples, &options, self.max_audio_samples) { Err(error) if self.gpu_failed(&error) => { self.recover_on_cpu(&error)?; self.session .transcribe_chunked_timed(&samples, &options, self.max_audio_samples) } result => result, } } /// The finest native timings this model gives, as a timed request needs /// them. Never the level a caller asked for. pub(crate) fn timestamps(&self) -> crate::transcription::transcript::TimestampLevel { crate::transcription::gguf_session::timestamp_level(self.finest_timestamps) } pub fn device_label(&self) -> &str { &self.device_label } /// Text and word times (ms from the clip's start) for a capture, in /// chunks the model takes whole. A model without word times gives its /// segments instead. pub fn transcribe_words(&mut self, samples: &[f32]) -> Result<(String, Vec)> { let transcript = self.timed(samples)?; let spans = if transcript.words.is_empty() { transcript.segments } else { transcript.words }; let words = spans .into_iter() .map(|word| (word.start_ms, word.end_ms, word.text)) .collect(); Ok((transcript.text, words)) } /// One meeting chunk with segment and word timings, padded as dictation /// pads a clip. pub(crate) fn transcribe_segments( &mut self, mut samples: Vec, ) -> Result { crate::dictation::pad_for_parakeet(&mut samples); self.timed(&samples) } /// Text, segments, and words, in chunks the model takes whole. fn timed(&mut self, samples: &[f32]) -> Result { match self.timed_here(samples) { Err(error) if self.gpu_failed(&error) => { self.recover_on_cpu(&error)?; self.timed_here(samples) } result => result, } } /// Whether this model runs on an integrated GPU slow enough that the /// CPU may be faster. fn slow_igpu(&self) -> bool { self.warm_ms > SLOW_WARM_MS && self .gpu .as_ref() .is_some_and(|gpu| gpu.device_type == transcribe_cpp::DeviceType::Igpu) } /// This model, or the same one on the CPU when the CPU runs it faster; /// then the GPU is remembered as slow, so later loads go straight to the /// CPU (#484). fn or_faster_cpu(self) -> Self { let cpu = match Self::load_on(&self.selection, Backend::Cpu, None, self.preference) { Ok(cpu) => cpu, Err(error) => { tracing::warn!( error = format!("{error:#}"), "could not time the model on the CPU; keeping the GPU" ); return self; } }; tracing::info!( gpu_ms = self.warm_ms, cpu_ms = cpu.warm_ms, "timed a warm 1.5 s run on the integrated GPU and the CPU" ); if cpu.warm_ms >= self.warm_ms { return self; } if let Some(gpu) = &self.gpu { gpu_health::record_slow( gpu, &format!( "a warm 1.5 s run took {} ms on the GPU and {} ms on the CPU", self.warm_ms, cpu.warm_ms ), ); } cpu } /// Whether `error` came from the GPU this model runs on failing. fn gpu_failed(&self, error: &color_eyre::eyre::Report) -> bool { self.gpu.is_some() && gpu_health::device_error(error) } /// Reloads this model on the CPU after its GPU failed mid-run (a hang /// or reset comes back as an error, #856), remembering the GPU once the /// CPU works. An out-of-memory failure is carried by the CPU model for /// the dictation engine to show in Settings (#1984). fn recover_on_cpu(&mut self, error: &color_eyre::eyre::Report) -> Result<()> { tracing::warn!( error = format!("{error:#}"), "the GPU failed while transcribing; reloading the model on the CPU" ); let gpu = self.gpu.take(); let mut cpu = Self::load_on(&self.selection, Backend::Cpu, None, self.preference)?; if let Some(gpu) = &gpu { if gpu_health::out_of_memory(error) { cpu.out_of_memory = Some(gpu_health::out_of_memory_failure( gpu, &format!("{error:#}"), )); } else { gpu_health::record(gpu, &format!("{error:#}")); } } gpu_health::set_auto_on_cpu(self.preference == TranscriptionDevice::Auto); *self = cpu; Ok(()) } fn timed_here( &mut self, samples: &[f32], ) -> Result { use crate::transcription::gguf_session::{chunk_ranges, sample_offset_ms}; use crate::transcription::transcript::TranscriptSegment; const CHUNK: usize = 30 * 16_000; let chunk = self.max_audio_samples.map_or(CHUNK, |max| max.min(CHUNK)); let options = RunOptions { timestamps: self.finest_timestamps, ..self.options.clone() }; let span = |offset: i64, t0: i64, t1: i64, text: String| { let text = text.trim().to_owned(); (!text.is_empty()).then(|| TranscriptSegment { start_ms: t0.max(0) + offset, end_ms: t1.max(t0) + offset, text, }) }; let mut timed = crate::transcription::transcript::Transcript::default(); let mut texts = Vec::new(); for range in chunk_ranges(samples, chunk) { let offset = sample_offset_ms(range.start); let transcript = self .session .run(&samples[range], &options) .wrap_err("transcription failed")?; let text = transcript.text.trim(); if !text.is_empty() { texts.push(text.to_owned()); } timed.segments.extend( transcript .segments .into_iter() .filter_map(|s| span(offset, s.t0_ms, s.t1_ms, s.text)), ); timed.words.extend( transcript .words .into_iter() .filter_map(|w| span(offset, w.t0_ms, w.t1_ms, w.text)), ); } timed.text = texts.join(" "); Ok(timed) } pub fn transcribe(&mut self, samples: &[f32]) -> Result { let run = |this: &mut Self| { this.session .transcribe_chunked(samples, &this.options, this.max_audio_samples) }; match run(self) { Err(error) if self.gpu_failed(&error) => { self.recover_on_cpu(&error)?; run(self) } result => result, } } } /// The local API's own model, loaded for the selection a host asks for /// when the dictation engine holds another one. #[derive(Default)] pub(crate) struct WarmLocal { active: Option, } impl WarmLocal { /// The loaded model, without switching or loading one. pub(crate) fn active(&mut self) -> Option<&mut LocalTranscriber> { self.active.as_mut() } pub(crate) fn activate( &mut self, selection: &TranscriptionSelection, ) -> Result<&mut LocalTranscriber> { if !self .active .as_ref() .is_some_and(|model| model.matches_selection(selection)) { self.active = None; self.active = Some(LocalTranscriber::load(selection)?); } Ok(self .active .as_mut() .expect("activated transcriber must be available")) } } /// A running listener's model: the one it transcribes with, and the one it /// changes to. A new selection loads on a worker thread while dictation goes /// on with the old model; the listener swaps it in once nothing records or /// waits on the old one. A model the host already prepared skips the load. /// A model loading on a worker thread. type Loading = std::sync::mpsc::Receiver>; pub(crate) struct ModelSwap { loaded: TranscriptionSelection, /// The device setting the running model loaded for. device: TranscriptionDevice, loading: Option<(TranscriptionSelection, TranscriptionDevice, Loading)>, ready: Option<(TranscriptionSelection, LocalTranscriber)>, /// A selection whose load beside the running model found the GPU full: /// the engine drops its model and loads this one in its place (#1170). reload: Option<(TranscriptionSelection, TranscriptionDevice)>, } impl ModelSwap { pub(crate) fn new(loaded: &TranscriptionSelection) -> Self { Self { loaded: super::custom_models::runnable(loaded), device: device(), loading: None, ready: None, reload: None, } } /// The selection and device setting the listener will transcribe with /// once swaps settle. fn target(&self) -> (&TranscriptionSelection, TranscriptionDevice) { self.ready .as_ref() .map(|(selection, model)| (selection, model.preference)) .or(self .reload .as_ref() .map(|(selection, device)| (selection, *device))) .or(self .loading .as_ref() .map(|(selection, device, _)| (selection, *device))) .unwrap_or((&self.loaded, self.device)) } /// A model the host loaded for `selection` (Linux prepares models /// beside the listener; Windows lets the listener load them). #[cfg_attr(target_os = "windows", allow(dead_code))] pub(crate) fn offer( &mut self, selection: &TranscriptionSelection, transcriber: LocalTranscriber, ) { self.loading = None; self.place(selection.clone(), transcriber); } /// Keeps a loaded model to swap in, unless it fell back to the CPU only /// because the running model fills the GPU: then it is dropped, and the /// engine reloads the selection once its own model is gone. fn place(&mut self, selection: TranscriptionSelection, transcriber: LocalTranscriber) { if transcriber.gpu_full { tracing::info!( "the GPU has no room for the new model beside the running one; loading it in its place" ); let device = transcriber.preference; drop(transcriber); self.ready = None; self.reload = Some((selection, device)); } else { self.reload = None; self.ready = Some((selection, transcriber)); } } /// Settings now select `selection`; loads it unless it is already the /// target. pub(crate) fn want(&mut self, selection: &TranscriptionSelection) { // An import that can't run stays saved; the listener runs the // default model meanwhile. let selection = super::custom_models::runnable(selection); let device = device(); if (&selection, device) == self.target() { return; } self.ready = None; self.reload = None; if selection == self.loaded && device == self.device { self.loading = None; return; } let (sender, receiver) = std::sync::mpsc::channel(); let load = selection.clone(); let spawned = std::thread::Builder::new() .name("hex-model-swap".into()) .spawn(move || { let _ = sender .send(LocalTranscriber::load(&load).map_err(|error| format!("{error:#}"))); }); match spawned { Ok(_) => self.loading = Some((selection, device, receiver)), Err(error) => tracing::warn!(%error, "could not load the new transcription model"), } } /// Collects a finished load; a failure keeps the current model. pub(crate) fn poll(&mut self) -> Option { let (_, _, receiver) = self.loading.as_ref()?; let result = match receiver.try_recv() { Ok(result) => result, Err(std::sync::mpsc::TryRecvError::Empty) => return None, Err(std::sync::mpsc::TryRecvError::Disconnected) => { Err("the model loader stopped unexpectedly".into()) } }; let (selection, _, _) = self.loading.take()?; match result { Ok(transcriber) => { self.place(selection, transcriber); None } Err(error) => Some(SwapFailed { wanted: selection, kept: self.loaded.clone(), error: format!("could not switch the transcription model: {error}"), }), } } /// The model to swap in now, if one is ready. pub(crate) fn take_ready(&mut self) -> Option { let (selection, transcriber) = self.ready.take()?; self.loaded = selection; self.device = transcriber.preference; Some(transcriber) } /// The selection the engine should load in place of its model, if the /// GPU had no room for both ([`TranscriptionEngine::reload`]). /// /// [`TranscriptionEngine::reload`]: crate::transcription::engine::TranscriptionEngine::reload pub(crate) fn take_reload(&mut self) -> Option { let (selection, device) = self.reload.take()?; self.loaded = selection.clone(); self.device = device; Some(selection) } } /// A model change that failed to load; the listener still runs `kept`. /// Windows hands it to the host, which puts settings back on `kept`; Linux /// only reports the error. #[derive(Debug)] #[cfg_attr(target_os = "linux", allow(dead_code))] pub(crate) struct SwapFailed { pub(crate) wanted: TranscriptionSelection, pub(crate) kept: TranscriptionSelection, pub(crate) error: String, } #[cfg(test)] mod model_swap_tests { use super::*; use crate::transcription::models::TranscriptionModelId; #[test] fn an_unchanged_selection_loads_nothing() { let selection = TranscriptionSelection { model: TranscriptionModelId::default(), ..Default::default() }; let mut swap = ModelSwap::new(&selection); swap.want(&selection); assert!(swap.loading.is_none()); assert!(swap.take_ready().is_none()); assert!(swap.poll().is_none()); } #[test] fn a_model_without_room_on_the_gpu_reloads_in_place_once() { let old = TranscriptionSelection::default(); let new = TranscriptionSelection { language: "de".into(), ..Default::default() }; let mut swap = ModelSwap::new(&old); swap.reload = Some((new.clone(), device())); // Already the target: nothing loads beside the running model. swap.want(&new); assert!(swap.loading.is_none()); assert!(swap.take_reload() == Some(new.clone())); assert!(swap.take_reload().is_none()); swap.want(&new); assert!(swap.loading.is_none()); assert!(swap.take_ready().is_none()); } }