YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
perf: reuse WhisperState across audio segments to reduce GPU contention
Louis Beaumont5e5ef7d77146
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rsindex 0b5f6e787..600fe6f2e 100644--- a/crates/screenpipe-audio/src/audio_manager/manager.rs+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs@@ -385,6 +385,15 @@ impl AudioManager {.expect("whisper model loading task panicked");info!("whisper model loaded successfully");+ // Create a single WhisperState and reuse it across all segments.+ // whisper_full_with_state() clears KV caches and results internally,+ // so there is no stale data between calls. This avoids repeated+ // Metal GPU buffer allocation/deallocation per segment.+ let mut whisper_state = whisper_context+ .create_state()+ .map_err(|e| anyhow!("failed to create initial whisper state: {}", e))?;+ info!("whisper state created (will be reused across segments)");+Ok(tokio::spawn(async move {while let Ok(audio) = whisper_receiver.recv() {info!("Received audio from device: {:?}", audio.device.name);@@ -458,7 +467,7 @@ impl AudioManager {deepgram_api_key.clone(),languages.clone(),&transcription_sender.clone(),- whisper_context.clone(),+ &mut whisper_state,metrics.clone(),).awaitdiff --git a/crates/screenpipe-audio/src/transcription/stt.rs b/crates/screenpipe-audio/src/transcription/stt.rsindex 82a44f172..8de6e9691 100644--- a/crates/screenpipe-audio/src/transcription/stt.rs+++ b/crates/screenpipe-audio/src/transcription/stt.rs@@ -15,14 +15,12 @@ use crate::utils::audio::resample;use crate::utils::ffmpeg::{get_new_file_path, write_audio_to_file};use crate::vad::VadEngine;use anyhow::Result;-#[cfg(target_os = "macos")]-use objc::rc::autoreleasepool;use screenpipe_core::Language;use std::path::PathBuf;use std::{sync::Arc, sync::Mutex as StdMutex};use tokio::sync::Mutex;use tracing::error;-use whisper_rs::WhisperContext;+use whisper_rs::WhisperState;use crate::{AudioInput, TranscriptionResult};@@ -36,7 +34,7 @@ pub async fn stt_sync(audio_transcription_engine: Arc<AudioTranscriptionEngine>,deepgram_api_key: Option<String>,languages: Vec<Language>,- whisper_context: Arc<WhisperContext>,+ whisper_state: &mut WhisperState,) -> Result<String> {let audio = audio.to_vec();@@ -49,7 +47,7 @@ pub async fn stt_sync(audio_transcription_engine,deepgram_api_key,languages,- whisper_context,+ whisper_state,).await}@@ -62,7 +60,7 @@ pub async fn stt(audio_transcription_engine: Arc<AudioTranscriptionEngine>,deepgram_api_key: Option<String>,languages: Vec<Language>,- whisper_context: Arc<WhisperContext>,+ whisper_state: &mut WhisperState,) -> Result<String> {let transcription: Result<String> =if audio_transcription_engine == AudioTranscriptionEngine::Deepgram.into() {@@ -79,12 +77,12 @@ pub async fn stt(device, e);// Fallback to Whisper- process_with_whisper(audio, languages.clone(), whisper_context).await+ process_with_whisper(audio, languages.clone(), whisper_state).await}}} else {// Existing Whisper implementation- process_with_whisper(audio, languages, whisper_context).await+ process_with_whisper(audio, languages, whisper_state).await};transcription@@ -102,7 +100,7 @@ pub async fn process_audio_input(deepgram_api_key: Option<String>,languages: Vec<Language>,output_sender: &crossbeam::channel::Sender<TranscriptionResult>,- whisper_context: Arc<WhisperContext>,+ whisper_state: &mut WhisperState,metrics: Arc<AudioPipelineMetrics>,) -> Result<()> {// Use the capture timestamp from when audio was recorded, not processing time.@@ -153,41 +151,17 @@ pub async fn process_audio_input(while let Some(segment) = segments.recv().await {let path = new_file_path.clone();- let transcription_result = if cfg!(target_os = "macos") {- #[cfg(target_os = "macos")]- {- let timestamp = timestamp + segment.start.round() as u64;- autoreleasepool(|| {- run_stt(- segment,- audio.device.clone(),- audio_transcription_engine.clone(),- deepgram_api_key.clone(),- languages.clone(),- path,- timestamp,- whisper_context.clone(),- )- })- .await?- }- #[cfg(not(target_os = "macos"))]- {- unreachable!("This code should not be reached on non-macOS platforms")- }- } else {- run_stt(- segment,- audio.device.clone(),- audio_transcription_engine.clone(),- deepgram_api_key.clone(),- languages.clone(),- path,- timestamp,- whisper_context.clone(),- )- .await?- };+ let transcription_result = run_stt(+ segment,+ audio.device.clone(),+ audio_transcription_engine.clone(),+ deepgram_api_key.clone(),+ languages.clone(),+ path,+ timestamp,+ whisper_state,+ )+ .await?;if output_sender.send(transcription_result).is_err() {break;@@ -206,7 +180,7 @@ pub async fn run_stt(languages: Vec<Language>,path: String,timestamp: u64,- whisper_context: Arc<WhisperContext>,+ whisper_state: &mut WhisperState,) -> Result<TranscriptionResult> {let audio = segment.samples.clone();let sample_rate = segment.sample_rate;@@ -217,7 +191,7 @@ pub async fn run_stt(audio_transcription_engine.clone(),deepgram_api_key.clone(),languages.clone(),- whisper_context,+ whisper_state,).await{diff --git a/crates/screenpipe-audio/src/transcription/whisper/batch.rs b/crates/screenpipe-audio/src/transcription/whisper/batch.rsindex f82548b7b..4a9f18bc8 100644--- a/crates/screenpipe-audio/src/transcription/whisper/batch.rs+++ b/crates/screenpipe-audio/src/transcription/whisper/batch.rs@@ -1,8 +1,7 @@use super::detect_language;use anyhow::Result;use screenpipe_core::Language;-use std::sync::Arc;-use whisper_rs::{FullParams, SamplingStrategy, WhisperContext};+use whisper_rs::{FullParams, SamplingStrategy, WhisperState};/// Processes audio data using the Whisper model to generate transcriptions.////// # Returns@@ -10,11 +9,8 @@ use whisper_rs::{FullParams, SamplingStrategy, WhisperContext};pub async fn process_with_whisper(audio: &[f32],languages: Vec<Language>,- whisper_context: Arc<WhisperContext>,+ whisper_state: &mut WhisperState,) -> Result<String> {- let mut whisper_state = whisper_context- .create_state()- .map_err(|e| anyhow::anyhow!("failed to create whisper state: {}", e))?;let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 0 });diff --git a/crates/screenpipe-audio/tests/accuracy_test.rs b/crates/screenpipe-audio/tests/accuracy_test.rsindex 055722f40..a764a1224 100644--- a/crates/screenpipe-audio/tests/accuracy_test.rs+++ b/crates/screenpipe-audio/tests/accuracy_test.rs@@ -131,6 +131,10 @@ async fn test_transcription_accuracy() {.await.unwrap();+ let mut whisper_state = whisper_context+ .create_state()+ .expect("failed to create whisper state");+let mut transcription = String::new();while let Some(segment) = segments.recv().await {let transcript = stt(@@ -140,7 +144,7 @@ async fn test_transcription_accuracy() {Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),None,vec![Language::English],- whisper_context.clone(),+ &mut whisper_state,).await.unwrap();diff --git a/crates/screenpipe-audio/tests/core_tests.rs b/crates/screenpipe-audio/tests/core_tests.rsindex 9547b5c16..3bd0c8e7e 100644--- a/crates/screenpipe-audio/tests/core_tests.rs+++ b/crates/screenpipe-audio/tests/core_tests.rs@@ -272,6 +272,10 @@ mod tests {.await.unwrap();+ let mut whisper_state = whisper_context+ .create_state()+ .expect("failed to create whisper state");+let mut transcription_result = String::new();while let Some(segment) = segments.recv().await {let transcript = stt(@@ -281,7 +285,7 @@ mod tests {Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),None,vec![Language::Arabic],- whisper_context.clone(),+ &mut whisper_state,).await.unwrap();@@ -374,6 +378,10 @@ mod tests {.await.unwrap();+ let mut whisper_state = whisper_context+ .create_state()+ .expect("failed to create whisper state");+let mut transcription = String::new();while let Some(segment) = segments.recv().await {let transcript = stt(@@ -383,7 +391,7 @@ mod tests {Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),None,vec![Language::English],- whisper_context.clone(),+ &mut whisper_state,).await.unwrap();