π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Reuse KV cache across chat turns
Manav Rathic4a04227c86d
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.ktindex 56e7f230a4..a100c14990 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt@@ -1234,11 +1234,11 @@ internal class ChatStoreActions()private fun buildSystemPrompt(nowMillis: Long = clock()): String {- val dateAndTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.getDefault())+ val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(nowMillis))val promptBody = state.value.developerSettings.systemPrompt.trim().ifEmpty { configDefaults.mobileSystemPromptBody }- return promptBody.replace(configDefaults.systemPromptDatePlaceholder, dateAndTime)+ return promptBody.replace(configDefaults.systemPromptDatePlaceholder, date)}companion object {diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.ktindex 63f912f9a9..835af058ad 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt@@ -44,7 +44,7 @@ fun SystemPromptSettingsScreen(.padding(EnsuSpacing.pageHorizontal.dp)) {Text(- text = "This prompt is used as-is. Use $datePlaceholder anywhere to insert the current date and time.",+ text = "This prompt is used as-is. Use $datePlaceholder anywhere to insert the current date.",style = EnsuTypography.small,color = EnsuColor.textMuted())@@ -59,7 +59,7 @@ fun SystemPromptSettingsScreen(.height(220.dp),placeholder = {Text(- text = "Example: You are a concise assistant. Current date and time: $datePlaceholder",+ text = "Example: You are a concise assistant. Current date: $datePlaceholder",style = EnsuTypography.body)},diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex fb5e0b3071..ebbcbc7ae5 100644--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -11,7 +11,7 @@ final class ChatViewModel: ObservableObject {private static let defaultTemperature: Float = 0.5private static let systemPromptDateFormatter: DateFormatter = {let formatter = DateFormatter()- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"+ formatter.dateFormat = "yyyy-MM-dd"return formatter}()private static let systemPromptDatePlaceholder = ConfigDefaults.shared.systemPromptDatePlaceholder@@ -24,9 +24,9 @@ final class ChatViewModel: ObservableObject {private static let sessionSummarySystemPrompt = ConfigDefaults.shared.sessionSummarySystemPromptprivate func systemPrompt() -> String {- let dateAndTime = Self.systemPromptDateFormatter.string(from: Date())+ let date = Self.systemPromptDateFormatter.string(from: Date())let promptBody = ModelSettingsStore.currentSystemPromptBody()- return promptBody.replacingOccurrences(of: Self.systemPromptDatePlaceholder, with: dateAndTime)+ return promptBody.replacingOccurrences(of: Self.systemPromptDatePlaceholder, with: date)}private let logger = EnsuLogging.shared.logger("ChatViewModel")diff --git a/mobile/native/apple/apps/ensu/Ensu/Settings/SettingsView.swift b/mobile/native/apple/apps/ensu/Ensu/Settings/SettingsView.swiftindex 87518d51b5..10902e3469 100644--- a/mobile/native/apple/apps/ensu/Ensu/Settings/SettingsView.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Settings/SettingsView.swift@@ -312,7 +312,7 @@ private struct SystemPromptSettingsView: View {VStack(alignment: .leading, spacing: EnsuSpacing.xxl) {sectionHeader("Prompt text")- Text("This prompt is used as-is. Use $date anywhere to insert the current date and time.")+ Text("This prompt is used as-is. Use $date anywhere to insert the current date.").font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)diff --git a/rust/apps/ensu/changes/kv-cache.md b/rust/apps/ensu/changes/kv-cache.mdnew file mode 100644index 0000000000..f7c04948bc--- /dev/null+++ b/rust/apps/ensu/changes/kv-cache.md@@ -0,0 +1 @@+- Faster replies in ongoing chats with a best-effort KV cache.diff --git a/rust/crates/ensu/src/config.rs b/rust/crates/ensu/src/config.rsindex 99f21c6b08..e22d135f86 100644--- a/rust/crates/ensu/src/config.rs+++ b/rust/crates/ensu/src/config.rs@@ -21,7 +21,7 @@ pub struct Defaults {}const SYSTEM_PROMPT_DATE_PLACEHOLDER: &str = "$date";-const MOBILE_SYSTEM_PROMPT_BODY: &str = "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";+const MOBILE_SYSTEM_PROMPT_BODY: &str = "You are Ensu, an AI assistant built by Ente. Current date: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";const DESKTOP_SYSTEM_PROMPT_BODY: &str = MOBILE_SYSTEM_PROMPT_BODY;const SESSION_SUMMARY_SYSTEM_PROMPT: &str = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.";diff --git a/rust/crates/ensu/src/llm/context.rs b/rust/crates/ensu/src/llm/context.rsindex 5d1ceb4a6d..3141bd5a36 100644--- a/rust/crates/ensu/src/llm/context.rs+++ b/rust/crates/ensu/src/llm/context.rs@@ -2,6 +2,7 @@ use llama_cpp_2::context::LlamaContext;use llama_cpp_2::context::params::LlamaContextParams;use llama_cpp_2::model::LlamaModel;use llama_cpp_2::mtmd::{MtmdContext, MtmdContextParams, mtmd_default_marker};+use llama_cpp_2::token::LlamaToken;use parking_lot::Mutex;use self_cell::self_cell;use serde::{Deserialize, Serialize};@@ -43,8 +44,13 @@ struct CachedMtmdContext {context: Arc<MtmdContext>,}+struct ContextState {+ cell: ContextCell,+ cached_tokens: Vec<LlamaToken>,+}+pub struct Context {- cell: Mutex<ContextCell>,+ state: Mutex<ContextState>,mtmd_context: Mutex<Option<CachedMtmdContext>>,}@@ -59,17 +65,24 @@ impl Context {builder: impl for<'a> FnOnce(&'a ModelRef) -> Result<LlamaContext<'a>, Error>,) -> Result<Self, Error> {ContextCell::try_new(owner, builder).map(|cell| Context {- cell: Mutex::new(cell),+ state: Mutex::new(ContextState {+ cell,+ cached_tokens: Vec::new(),+ }),mtmd_context: Mutex::new(None),})}- pub(super) fn with_context_mut<R>(+ pub(super) fn with_context_and_cache_mut<R>(&self,- func: impl for<'a, 'b> FnOnce(&'b mut LlamaContext<'a>) -> R,+ func: impl for<'a, 'b> FnOnce(&'b mut LlamaContext<'a>, &'b mut Vec<LlamaToken>) -> R,) -> R {- let mut guard = self.cell.lock();- guard.with_dependent_mut(|_owner, context| func(context))+ let mut state = self.state.lock();+ let ContextState {+ cell,+ cached_tokens,+ } = &mut *state;+ cell.with_dependent_mut(|_owner, context| func(context, cached_tokens))}pub(super) fn cached_mtmd_context(@@ -113,6 +126,10 @@ impl Context {});Ok(mtmd_ctx)}++ pub(super) fn invalidate_cache(&self) {+ self.state.lock().cached_tokens.clear();+ }}fn mtmd_cache_key_and_params(@@ -189,7 +206,7 @@ impl Context {media_marker: Option<String>,) -> Result<(), Error> {let marker = media_marker.unwrap_or_else(|| mtmd_default_marker().to_string());- self.with_context_mut(|ctx| {+ self.with_context_and_cache_mut(|ctx, _| {self.cached_mtmd_context(ctx.model, &mmproj_path, &marker).map(|_| ())})diff --git a/rust/crates/ensu/src/llm/generate.rs b/rust/crates/ensu/src/llm/generate.rsindex 4ed7e8ee64..48388812e4 100644--- a/rust/crates/ensu/src/llm/generate.rs+++ b/rust/crates/ensu/src/llm/generate.rs@@ -326,6 +326,7 @@ fn run_generation_loop(max_tokens: usize,stop_sequences: &[String],generated_tokens_count: &mut i32,+ mut cached_tokens: Option<&mut Vec<LlamaToken>>,mut pos: i32,mut logits_index: i32,) -> Result<(), Error> {@@ -375,10 +376,19 @@ fn run_generation_loop(op: "Failed to add token",message: err.to_string(),})?;- ctx.decode(&mut step_batch).map_err(|err| Error::Llama {- op: "Decode failed",- message: err.to_string(),- })?;+ if let Err(err) = ctx.decode(&mut step_batch) {+ ctx.clear_kv_cache();+ if let Some(cached) = cached_tokens.as_deref_mut() {+ cached.clear();+ }+ return Err(Error::Llama {+ op: "Decode failed",+ message: err.to_string(),+ });+ }+ if let Some(cached) = cached_tokens.as_deref_mut() {+ cached.push(token);+ }logits_index = 0;pos += 1;@@ -511,7 +521,7 @@ fn generate_chat_stream(let mut generated_tokens_count: i32 = 0;let result = match catch_unwind(AssertUnwindSafe(|| {- context.with_context_mut(|ctx| -> Result<(), Error> {+ context.with_context_and_cache_mut(|ctx, cached_tokens| -> Result<(), Error> {let add_assistant = add_assistant.unwrap_or(true);let mut messages = messages;let image_paths = image_paths.unwrap_or_default();@@ -594,9 +604,14 @@ fn generate_chat_stream(return Err(Error::InvalidInput("Context batch size is 0".to_string()));}- ctx.clear_kv_cache();+ let keep = append_only_prefix_len(cached_tokens, &prompt_tokens);- let mut token_offset = 0usize;+ if keep == 0 {+ ctx.clear_kv_cache();+ cached_tokens.clear();+ }++ let mut token_offset = keep;let mut logits_index: i32 = 0;while token_offset < prompt_tokens.len() {check_cancelled(&cancel_flag)?;@@ -613,10 +628,18 @@ fn generate_chat_stream(message: err.to_string(),})?;}- ctx.decode(&mut batch).map_err(|err| Error::Llama {- op: "Prompt decode failed",- message: err.to_string(),- })?;++ if let Err(err) = ctx.decode(&mut batch) {+ ctx.clear_kv_cache();+ cached_tokens.clear();+ return Err(Error::Llama {+ op: "Prompt decode failed",+ message: err.to_string(),+ });+ }++ cached_tokens.extend_from_slice(chunk);+if end == prompt_tokens.len() {logits_index = (chunk.len() - 1) as i32;}@@ -636,6 +659,7 @@ fn generate_chat_stream(max_tokens,&stop_sequences,&mut generated_tokens_count,+ Some(cached_tokens),pos,logits_index,)?;@@ -710,6 +734,7 @@ fn generate_chat_stream(}ctx.clear_kv_cache();+ cached_tokens.clear();check_cancelled(&cancel_flag)?;let n_past = chunks@@ -740,6 +765,7 @@ fn generate_chat_stream(max_tokens,&stop_sequences,&mut generated_tokens_count,+ None,n_past,-1,)?;@@ -748,7 +774,10 @@ fn generate_chat_stream(})})) {Ok(inner) => inner,- Err(_) => Err(Error::Panicked),+ Err(_) => {+ context.invalidate_cache();+ Err(Error::Panicked)+ }};result?;@@ -766,6 +795,14 @@ fn generate_chat_stream(Ok(summary)}+fn append_only_prefix_len(cached: &[LlamaToken], prompt: &[LlamaToken]) -> usize {+ if !cached.is_empty() && cached.len() < prompt.len() && prompt.starts_with(cached) {+ cached.len()+ } else {+ 0+ }+}+pub fn cancel(job_id: JobId) {if job_id <= 0 {cancel_all();@@ -778,7 +815,12 @@ pub fn cancel(job_id: JobId) {#[cfg(test)]mod tests {- use super::StreamDecoder;+ use super::{StreamDecoder, append_only_prefix_len};+ use llama_cpp_2::token::LlamaToken;++ fn tokens(ids: &[i32]) -> Vec<LlamaToken> {+ ids.iter().copied().map(LlamaToken).collect()+ }#[test]fn stream_decoder_emits_complete_utf8() {@@ -791,4 +833,25 @@ mod tests {assert_eq!(step.text.as_deref(), Some("π"));assert!(!step.stop);}++ #[test]+ fn only_strict_extensions_reuse_cache() {+ assert_eq!(append_only_prefix_len(&[], &tokens(&[1])), 0);+ assert_eq!(+ append_only_prefix_len(&tokens(&[1, 2]), &tokens(&[1, 2])),+ 0+ );+ assert_eq!(+ append_only_prefix_len(&tokens(&[1, 2, 3]), &tokens(&[1, 2])),+ 0+ );+ assert_eq!(+ append_only_prefix_len(&tokens(&[1, 2]), &tokens(&[1, 3, 4])),+ 0+ );+ assert_eq!(+ append_only_prefix_len(&tokens(&[1, 2]), &tokens(&[1, 2, 3])),+ 2+ );+ }}diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsxindex eebdc3ead4..c186a245a2 100644--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx@@ -990,8 +990,8 @@ export const ChatDialogs = memo(sx={{ color: "text.muted" }}>This prompt is used as-is. Use $date anywhere to- insert the current date and time. Leave blank to- use the default prompt.+ insert the current date. Leave blank to use the+ default prompt.</Typography><TextFieldfullWidth@@ -999,7 +999,7 @@ export const ChatDialogs = memo(minRows={10}maxRows={18}label="Prompt text"- placeholder="You are a concise assistant. Current date and time: $date"+ placeholder="You are a concise assistant. Current date: $date"value={draftSystemPrompt}onChange={(event) =>setDraftSystemPrompt(event.target.value)diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 5fcc2aff44..db237fa9a8 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -233,14 +233,14 @@ const toSafeBlobPart = (bytes: Uint8Array): ArrayBuffer => {};const DEFAULT_CHAT_SYSTEM_PROMPT_BODY =- "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";+ "You are Ensu, an AI assistant built by Ente. Current date: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";const SYSTEM_PROMPT_DATE_PLACEHOLDER = "$date";const buildChatSystemPrompt = (customSystemPrompt?: string) => {- const dateAndTime = new Date().toLocaleString();+ const date = new Date().toLocaleDateString();const promptBody =customSystemPrompt?.trim() || DEFAULT_CHAT_SYSTEM_PROMPT_BODY;- return promptBody.split(SYSTEM_PROMPT_DATE_PLACEHOLDER).join(dateAndTime);+ return promptBody.split(SYSTEM_PROMPT_DATE_PLACEHOLDER).join(date);};const SESSION_TITLE_PROMPT =