A high-performance inference engine for AI models
Context cache mode api (#40)
LuckyIYI1315ad8df554
diff --git a/crates/cli/src/server/chat_completions.rs b/crates/cli/src/server/chat_completions.rsindex 4aa113269..35a627673 100644--- a/crates/cli/src/server/chat_completions.rs+++ b/crates/cli/src/server/chat_completions.rs@@ -1,7 +1,4 @@-use std::{- rc::Rc,- time::{SystemTime, UNIX_EPOCH},-};+use std::time::{SystemTime, UNIX_EPOCH};use rocket::{State, post, serde::json::Json};use serde::{Deserialize, Serialize};@@ -27,7 +24,6 @@ pub struct ChatMessage {pub struct ChatCompletionRequest {pub messages: Vec<ChatMessage>,pub max_completion_tokens: Option<u64>,- pub system_prompt_key: Option<String>,}#[derive(Serialize, Deserialize, Clone)]@@ -61,7 +57,6 @@ pub fn handle_chat_completions(" Max tokens: {}",request.max_completion_tokens.unwrap_or(2048));- println!(" System prompt key: {:?}", request.system_prompt_key);for (i, msg) in request.messages.iter().enumerate() {let content_preview = if msg.content.len() > 10000 {@@ -73,7 +68,6 @@ pub fn handle_chat_completions(}let model_name = state.model_name.clone();- let system_prompt_key = request.system_prompt_key;let tokens_limit = request.max_completion_tokens.unwrap_or(2048);let messages: Vec<Message> = request.messages@@ -91,62 +85,8 @@ pub fn handle_chat_completions(let start_time = std::time::Instant::now();let mut session = state.session_wrapper.lock();- let output = if let Some(key) = system_prompt_key {- let context = state.cache.lock().unwrap().get(&key);- match session.extend(input, context.as_deref(), run_config) {- Ok((output, new_context)) => {- state- .cache- .lock()- .unwrap()- .insert(key.clone(), Rc::new(new_context));- output- },- Err(e) => {- eprintln!("❌ [{}] Session extend error: {}", id, e);- // Return error response- let error_response = ChatCompletionResponse {- id: id.clone(),- object: "chat.completion".to_string(),- created: SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs() as i64,- model: model_name.clone(),- choices: vec![ChatCompletionChoice {- index: 0,- message: ChatMessage {- content: format!("Error: {}", e),- role: Role::Assistant,- },- finish_reason: "error".to_string(),- }],- stats: Stats {- prefill_stats: StepStats {- duration: 0.0,- suffix_length: 0,- tokens_count: 0,- tokens_per_second: 0.0,- processed_tokens_per_second: 0.0,- model_run: RunStats {- count: 0,- average_duration: 0.0,- },- run: None,- },- generate_stats: None,- total_stats: TotalStats {- duration: 0.0,- tokens_count_input: 0,- tokens_count_output: 0,- },- },- };- return Json(error_response);- },- }- } else {- match session.run_with_context(input, None, run_config) {+ let output =+ match session.run(input, run_config, None::<fn(Output) -> bool>) {Ok(output) => output,Err(e) => {eprintln!("❌ [{}] Session run error: {}", id, e);@@ -190,8 +130,7 @@ pub fn handle_chat_completions(};return Json(error_response);},- }- };+ };let processing_time = start_time.elapsed();diff --git a/crates/cli/src/server/main.rs b/crates/cli/src/server/main.rsindex 524a3aed7..356109563 100644--- a/crates/cli/src/server/main.rs+++ b/crates/cli/src/server/main.rs@@ -5,7 +5,6 @@ use rocket::{Config, config::LogLevel, log::private as log, routes};use crate::server::{SessionState, SessionWrapper, handle_chat_completions, load_session,- state::ContextCache,};struct SilentLogger;@@ -58,7 +57,6 @@ pub async fn run_server(model_path: String) {let state = SessionState {model_name,session_wrapper: SessionWrapper::new(session),- cache: std::sync::Mutex::new(ContextCache::new(5)),};let _ = rocket::custom(config)diff --git a/crates/cli/src/server/state.rs b/crates/cli/src/server/state.rsindex 12a904876..b9b5baafc 100644--- a/crates/cli/src/server/state.rs+++ b/crates/cli/src/server/state.rs@@ -1,57 +1,8 @@-use std::{- collections::{HashMap, VecDeque},- path::PathBuf,- rc::Rc,- sync::Mutex,-};+use std::{path::PathBuf, sync::Mutex};use console::Style;use indicatif::{ProgressBar, ProgressStyle};-use uzu::session::{Session, config::DecodingConfig, helpers::Context};--pub struct ContextCache {- pub map: HashMap<String, Rc<Context>>,- pub order: VecDeque<String>,- pub capacity: usize,-}--impl ContextCache {- pub fn new(capacity: usize) -> Self {- Self {- map: HashMap::new(),- order: VecDeque::new(),- capacity,- }- }-- pub fn insert(- &mut self,- key: String,- context: Rc<Context>,- ) -> Option<(String, Rc<Context>)> {- if self.map.contains_key(&key) {- return None;- }- self.map.insert(key.clone(), context);- self.order.push_back(key.clone());-- if self.order.len() > self.capacity {- if let Some(old_key) = self.order.pop_front() {- if let Some(old_context) = self.map.remove(&old_key) {- return Some((old_key, old_context));- }- }- }- None- }-- pub fn get(- &self,- key: &str,- ) -> Option<Rc<Context>> {- self.map.get(key).cloned()- }-}+use uzu::session::{Session, config::DecodingConfig};pub struct SessionWrapper(Mutex<Session>);unsafe impl Send for SessionWrapper {}@@ -69,7 +20,6 @@ impl SessionWrapper {pub struct SessionState {pub model_name: String,pub session_wrapper: SessionWrapper,- pub cache: Mutex<ContextCache>,}unsafe impl Send for SessionState {}diff --git a/crates/uzu/src/backends/metal/forward_pass/kv_cache.rs b/crates/uzu/src/backends/metal/forward_pass/kv_cache.rsindex 2a16a8381..c8c444e21 100644--- a/crates/uzu/src/backends/metal/forward_pass/kv_cache.rs+++ b/crates/uzu/src/backends/metal/forward_pass/kv_cache.rs@@ -448,12 +448,11 @@ impl KVCache {}}- pub fn clone_with_prefix_len(+ pub fn clone(&self,context: &MTLContext,- prefix_len: usize,) -> Self {- let new_total_len = prefix_len + self.max_suffix_length;+ let mut max_prefix_capacity_across_layers = 0usize;let data: Box<[KVCacheLayer]> = self.data.iter()@@ -462,16 +461,17 @@ impl KVCache {let num_groups = shape[0];let head_dim = shape[2];let dtype = layer.keys.borrow().data_type();- let new_shape = [num_groups, new_total_len, head_dim];+ let copy_rows = layer.prefix_segment_length();+ let new_total_len = copy_rows + self.max_suffix_length;+ if copy_rows > max_prefix_capacity_across_layers {+ max_prefix_capacity_across_layers = copy_rows;+ }++ let new_shape = [num_groups, new_total_len, head_dim];let mut new_keys = context.array(&new_shape, dtype);let mut new_values = context.array(&new_shape, dtype);- let mut copy_rows = layer.prefix_segment_length();- if let Some(window_length) = layer.window_length() {- copy_rows = std::cmp::min(copy_rows, window_length);- }-if copy_rows > 0 {new_keys.copy_slice(&layer.keys.borrow(),@@ -501,7 +501,7 @@ impl KVCache {Self {max_suffix_length: self.max_suffix_length,- max_prefix_length: prefix_len,+ max_prefix_length: max_prefix_capacity_across_layers,data,}}diff --git a/crates/uzu/src/generator/generator.rs b/crates/uzu/src/generator/generator.rsindex a5f71fe0d..66f9d57ad 100644--- a/crates/uzu/src/generator/generator.rs+++ b/crates/uzu/src/generator/generator.rs@@ -67,6 +67,7 @@ impl Generator {tokens: Vec<u64>,sampling_method: SamplingMethod,prefix_offset: usize,+ sample_suffix: bool,) -> Result<PrefillResult, Error> {assert!(!tokens.is_empty());@@ -172,7 +173,7 @@ impl Generator {..step_end_token_index).map(|idx| idx + prefix_offset).collect();- if step == number_of_prefill_steps - 1 {+ if step == number_of_prefill_steps - 1 && sample_suffix {// Exclude the last token because it belongs to the suffix for sampling.positions_for_step.pop();}@@ -204,6 +205,13 @@ impl Generator {}let mut final_state = last_state.ok_or(Error::PrefillFailed)?;+ if !sample_suffix {+ self.sync_prefix();+ return Ok(PrefillResult {+ tokens: Vec::new(),+ forwardpass_durations: run_times,+ });+ }let sampled_tokens = self.sample(&mut final_state)?;let last_suffix_start =diff --git a/crates/uzu/src/session/config/decoding_config.rs b/crates/uzu/src/session/config/decoding_config.rsindex 227ce5301..350feff98 100644--- a/crates/uzu/src/session/config/decoding_config.rs+++ b/crates/uzu/src/session/config/decoding_config.rs@@ -1,12 +1,13 @@use crate::session::{config::SpeculatorConfig,- parameter::{ContextLength, PrefillStepSize, SamplingSeed},+ parameter::{ContextLength, ContextMode, PrefillStepSize, SamplingSeed},};#[derive(Clone)]pub struct DecodingConfig {- pub prefill_step_size: PrefillStepSize,+ pub context_mode: ContextMode,pub context_length: ContextLength,+ pub prefill_step_size: PrefillStepSize,pub speculator_config: SpeculatorConfig,pub sampling_seed: SamplingSeed,pub allow_pre_encode: bool,@@ -14,15 +15,17 @@ pub struct DecodingConfig {impl DecodingConfig {pub fn new(- prefill_step_size: PrefillStepSize,+ context_mode: ContextMode,context_length: ContextLength,+ prefill_step_size: PrefillStepSize,speculator_config: SpeculatorConfig,sampling_seed: SamplingSeed,allow_pre_encode: bool,) -> Self {Self {- prefill_step_size,+ context_mode,context_length,+ prefill_step_size,speculator_config,sampling_seed,allow_pre_encode,@@ -37,11 +40,74 @@ impl DecodingConfig {impl Default for DecodingConfig {fn default() -> Self {Self {- prefill_step_size: PrefillStepSize::default(),+ context_mode: ContextMode::default(),context_length: ContextLength::default(),+ prefill_step_size: PrefillStepSize::default(),speculator_config: SpeculatorConfig::default(),sampling_seed: SamplingSeed::default(),allow_pre_encode: true,}}}++impl DecodingConfig {+ pub fn with_context_mode(+ &self,+ context_mode: ContextMode,+ ) -> Self {+ Self {+ context_mode,+ ..self.clone()+ }+ }++ pub fn with_context_length(+ &self,+ context_length: ContextLength,+ ) -> Self {+ Self {+ context_length,+ ..self.clone()+ }+ }++ pub fn with_prefill_step_size(+ &self,+ prefill_step_size: PrefillStepSize,+ ) -> Self {+ Self {+ prefill_step_size,+ ..self.clone()+ }+ }++ pub fn with_speculator_config(+ &self,+ speculator_config: SpeculatorConfig,+ ) -> Self {+ Self {+ speculator_config,+ ..self.clone()+ }+ }++ pub fn with_sampling_seed(+ &self,+ sampling_seed: SamplingSeed,+ ) -> Self {+ Self {+ sampling_seed,+ ..self.clone()+ }+ }++ pub fn with_allow_pre_encode(+ &self,+ allow_pre_encode: bool,+ ) -> Self {+ Self {+ allow_pre_encode,+ ..self.clone()+ }+ }+}diff --git a/crates/uzu/src/session/config/mod.rs b/crates/uzu/src/session/config/mod.rsindex 89c713ed1..28ba4b356 100644--- a/crates/uzu/src/session/config/mod.rs+++ b/crates/uzu/src/session/config/mod.rs@@ -1,6 +1,7 @@mod decoding_config;mod run_config;mod speculator_config;+pub use decoding_config::DecodingConfig;pub use run_config::RunConfig;pub use speculator_config::SpeculatorConfig;diff --git a/crates/uzu/src/session/parameter/context_mode.rs b/crates/uzu/src/session/parameter/context_mode.rsnew file mode 100644index 000000000..38244388d--- /dev/null+++ b/crates/uzu/src/session/parameter/context_mode.rs@@ -0,0 +1,16 @@+use crate::session::types::Input;++#[derive(Clone, Debug)]+pub enum ContextMode {+ None,+ Static {+ input: Input,+ },+ Dynamic,+}++impl Default for ContextMode {+ fn default() -> Self {+ ContextMode::None+ }+}diff --git a/crates/uzu/src/session/parameter/mod.rs b/crates/uzu/src/session/parameter/mod.rsindex 6bd57ab0b..7a0299bcf 100644--- a/crates/uzu/src/session/parameter/mod.rs+++ b/crates/uzu/src/session/parameter/mod.rs@@ -1,9 +1,11 @@mod context_length;+mod context_mode;mod prefill_step_size;mod resolvable_value;mod sampling_policy;mod sampling_seed;pub use context_length::ContextLength;+pub use context_mode::ContextMode;pub use prefill_step_size::PrefillStepSize;pub use resolvable_value::{ConfigResolvableValue, ResolvableValue};pub use sampling_policy::{SamplingMethod, SamplingPolicy};diff --git a/crates/uzu/src/session/session.rs b/crates/uzu/src/session/session.rsindex c0d689726..ad88dd710 100644--- a/crates/uzu/src/session/session.rs+++ b/crates/uzu/src/session/session.rs@@ -15,7 +15,7 @@ use crate::{Context, InputProcessor, InputProcessorDefault, OutputParser,is_directory_fits_ram,},- parameter::ConfigResolvableValue,+ parameter::{ConfigResolvableValue, ContextMode},types::{Error, FinishReason, Input, Output, RunStats, Stats, StepStats,TotalStats,@@ -31,6 +31,7 @@ pub struct Session {input_processor: Box<dyn InputProcessor>,output_parser: OutputParser,generator: Option<Generator>,+ static_context: Option<Context>,}impl Session {@@ -85,6 +86,7 @@ impl Session {input_processor: Box::new(input_processor),output_parser,generator: Some(generator),+ static_context: None,})}@@ -97,17 +99,56 @@ impl Session {whereF: Fn(Output) -> bool,{- let generator =- self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;- generator.reset_state();+ let context_mode = self+ .generator+ .as_ref()+ .ok_or(Error::GeneratorNotLoaded)?+ .decoding_config+ .context_mode+ .clone();++ match &context_mode {+ ContextMode::None => {+ let generator =+ self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;+ generator.reset_state();+ },+ ContextMode::Static {+ input,+ } => {+ if self.static_context.is_none() {+ let mut prefill_config = config.clone();+ prefill_config.tokens_limit = 0;+ let (_out, ctx) =+ self.extend(input.clone(), None, prefill_config)?;+ self.static_context = Some(ctx);+ }+ let tmp = self.static_context.take();+ if let Some(ref ctx) = tmp {+ self.reconfigure_generator(Some(ctx))?;+ }+ self.static_context = tmp;+ },+ ContextMode::Dynamic => {},+ }+let output = self.run_internal(input, config, progress)?;- let generator =- self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;- generator.reset_state();++ match context_mode {+ ContextMode::None+ | ContextMode::Static {+ ..+ } => {+ let generator =+ self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;+ generator.reset_state();+ },+ ContextMode::Dynamic => {},+ }Ok(output)}- pub fn extend(+ fn extend(&mut self,input: Input,context: Option<&Context>,@@ -123,21 +164,6 @@ impl Session {Ok((output, new_context))}- pub fn run_with_context(- &mut self,- input: Input,- context: Option<&Context>,- config: RunConfig,- ) -> Result<Output, Error> {- self.reconfigure_generator(context)?;- let output =- self.run_internal(input, config, None::<fn(Output) -> bool>)?;- let generator =- self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;- generator.reset_state();- Ok(output)- }-fn run_internal<F>(&mut self,input: Input,@@ -170,7 +196,7 @@ impl Session {return Err(Error::ContextLengthExceeded);}- let prefix_len_before = generator.prefix_len();+ let prefix_len_before = generator.tokens.len().saturating_sub(1);let eos_tokens: Vec<u64> = self.model_metadata@@ -223,10 +249,12 @@ impl Session {let prefill_start = Instant::now();let prefix_offset = generator.tokens.len();+ let sample_suffix = config.tokens_limit > 0;let prefill_result = generator.prefill(tokens.clone(),sampling_method,prefix_offset,+ sample_suffix,)?;let prefill_tokens = prefill_result.tokens.clone();let prefill_duration = prefill_start.elapsed().as_secs_f64();@@ -370,12 +398,11 @@ impl Session {fn build_context_from_generator(&self) -> Result<Context, Error> {let generator =self.generator.as_ref().ok_or(Error::GeneratorNotLoaded)?;- let prefix_len = generator.prefix_len();let kv_cache = generator.context.kv_cache.borrow()- .clone_with_prefix_len(&generator.context.mtl_context, prefix_len);+ .clone(&generator.context.mtl_context);let context = Context::new(generator.tokens.clone(),kv_cache,diff --git a/crates/uzu/src/session/types/input.rs b/crates/uzu/src/session/types/input.rsindex 2865faded..837d5e677 100644--- a/crates/uzu/src/session/types/input.rs+++ b/crates/uzu/src/session/types/input.rs@@ -1,6 +1,6 @@use crate::session::types::{Message, Role};-#[derive(Debug)]+#[derive(Debug, Clone)]pub enum Input {Text(String),Messages(Vec<Message>),diff --git a/crates/uzu/src/tracer/tracer.rs b/crates/uzu/src/tracer/tracer.rsindex 7c5d9e5d1..93fbb1626 100644--- a/crates/uzu/src/tracer/tracer.rs+++ b/crates/uzu/src/tracer/tracer.rs@@ -29,7 +29,7 @@ use crate::{session::{config::{DecodingConfig, SpeculatorConfig},parameter::{- ConfigResolvableValue, ContextLength, PrefillStepSize,+ ConfigResolvableValue, ContextLength, ContextMode, PrefillStepSize,ResolvableValue, SamplingSeed,},},@@ -147,8 +147,9 @@ impl Tracer {pub fn new(model_path: &Path) -> Self {let prefill_step_size = Self::determine_prefill_step_size(model_path);let decoding_config = DecodingConfig::new(- PrefillStepSize::Custom(prefill_step_size),+ ContextMode::default(),ContextLength::default(),+ PrefillStepSize::Custom(prefill_step_size),SpeculatorConfig::default(),SamplingSeed::default(),false,@@ -176,8 +177,9 @@ impl Tracer {) -> Self {let prefill_step_size = Self::determine_prefill_step_size(model_path);let decoding_config = DecodingConfig::new(- PrefillStepSize::Custom(prefill_step_size),+ ContextMode::default(),max_prefix_length,+ PrefillStepSize::Custom(prefill_step_size),SpeculatorConfig::default(),sampling_seed,false,diff --git a/crates/uzu/tests/context_kv_cache_test.rs b/crates/uzu/tests/context_kv_cache_test.rsdeleted file mode 100644index 403b1305f..000000000--- a/crates/uzu/tests/context_kv_cache_test.rs+++ /dev/null@@ -1,294 +0,0 @@-use std::{path::PathBuf, rc::Rc};--use uzu::session::{- Session,- config::{DecodingConfig, RunConfig},- helpers::Context,- parameter::{SamplingMethod, SamplingPolicy},- types::{Input, Output},-};--mod common;--fn model_path() -> PathBuf {- common::get_test_model_path()-}--#[test]-fn test_context_reuse() {- let mut session = create_session();-- let system_prompt = "Name: Alice. Age: 30. Occupation: Engineer.";- let context = build_context(&mut session, system_prompt);-- let answer = ask_with_context(- &mut session,- Some(context),- "What is Alice's occupation?",- );-- println!("Answer: {}", answer);- assert!(answer.to_lowercase().contains("engineer"));-}--#[test]-fn test_multiple_contexts() {- let mut session = create_session();-- let ctx1 =- build_context(&mut session, "Name: Alice. Occupation: Engineer.");-- let ctx2 = build_context(&mut session, "Name: Alice. Occupation: Artist.");-- let answer1 = ask_with_context(- &mut session,- Some(ctx1),- "What is Alice's occupation?",- );- println!("Answer 1: {}", answer1);- assert!(answer1.to_lowercase().contains("engineer"));-- let answer2 = ask_with_context(- &mut session,- Some(ctx2),- "What is Alice's occupation?",- );- println!("Answer 2: {}", answer2);- assert!(answer2.to_lowercase().contains("artist"));-}--#[test]-fn test_context_extension() {- let mut session = create_session();- let initial_context =- build_context(&mut session, "Name: Dave. Occupation: Nurse.");-- let answer_initial = ask_with_context(- &mut session,- Some(initial_context.clone()),- "What is Dave's occupation?",- );- assert!(answer_initial.to_lowercase().contains("nurse"));- println!("Answer initial: {}", answer_initial);-- // Extend the context with new information- let (_, extended_context) = session- .extend(- Input::Text("Update: Name: Dave. Occupation: Doctor.".to_string()),- Some(initial_context.as_ref()),- RunConfig::new(- 1,- true,- SamplingPolicy::Custom {- value: SamplingMethod::Greedy,- },- ),- )- .unwrap();-- let answer_updated = ask_with_context(- &mut session,- Some(Rc::new(extended_context)),- "What is Dave's occupation?",- );- println!("Answer updated: {}", answer_updated);- assert!(answer_updated.to_lowercase().contains("doctor"));-}--#[test]-fn test_deep_copy_isolated() {- let mut session = create_session();-- let context =- build_context(&mut session, "Name: Alice. Occupation: Singer.");-- let answer_no_ctx1 =- ask_without_context(&mut session, "What is Alice's occupation?");- println!("Answer without context #1: {}", answer_no_ctx1);-- let answer_with_ctx = ask_with_context(- &mut session,- Some(context),- "What is Alice's occupation?",- );- println!("Answer with context: {}", answer_with_ctx);-- let answer_no_ctx2 =- ask_without_context(&mut session, "What is Alice's occupation?");- println!("Answer without context #2: {}", answer_no_ctx2);-- assert_eq!(answer_no_ctx1, answer_no_ctx2);- assert_ne!(answer_with_ctx, answer_no_ctx1);- assert!(answer_with_ctx.to_lowercase().contains("singer"));-}--#[test]-fn test_performance_cached_vs_plain() {- let mut session = create_session();- let system_prompt = "- Eve Smith is a talented 25-year-old professional dancer who lives in New York City.- She was born on March 15th, 1999, in a small town called Middlebury in Vermont to parents Robert and Sarah Smith.- Eve has beautiful emerald green eyes and long auburn hair that she often wears in a bun for performances.- She stands 5 feet 6 inches tall and weighs 125 pounds, with an athletic dancer's build.- She graduated from Juilliard School with a Bachelor of Fine Arts in Dance in 2021, graduating summa cum laude.- Eve specializes in contemporary and ballet dance styles, though she also enjoys jazz, hip-hop, and modern dance.- She currently works with the Manhattan Dance Company as a principal dancer, earning $85,000 per year.- Her favorite ballet is Swan Lake, and her favorite contemporary piece is Martha Graham's Appalachian Spring.- In her free time, Eve loves to paint watercolor landscapes and has sold several pieces at local art galleries for $300-500 each.- She lives in a cozy 600-square-foot studio apartment in Brooklyn's Park Slope neighborhood, paying $2,800 per month in rent.- She shares her apartment with her rescue cat named Luna, a 3-year-old gray tabby she adopted from the ASPCA.- Eve is also passionate about teaching dance to underprivileged children and volunteers at the Downtown Community Center every Saturday morning from 9 AM to 12 PM.- Her biggest dream is to choreograph her own full-length ballet production called 'Seasons of Change' someday.- Eve drives a blue 2019 Honda Civic and her favorite coffee shop is Blue Bottle Coffee on 5th Avenue.- She has a best friend named Maya Rodriguez who works as a photographer in Manhattan.- Eve's favorite food is Thai green curry, and she's allergic to shellfish and peanuts.- She practices yoga every Tuesday and Thursday at 7 PM at Dharma Yoga Center.- Eve's phone number is 555-123-4567 and her email is [email protected].- She has performed in 12 professional productions and won the Young Artist Award in 2022.- Eve's Instagram handle is @evesmithdancer with 15,000 followers.- She speaks fluent English and conversational French, having studied abroad in Paris for one semester.- Her favorite season is autumn, and her lucky number is 7.- Eve wears size 7.5 shoes and prefers Bloch pointe shoes for ballet performances.- She has a small scar on her left knee from a childhood bicycle accident.- Every Sunday, she calls her grandmother Margaret who lives in a nursing home in Vermont. ";-- let questions = [- "What is Eve's occupation?",- "How old is Eve?",- "What is Eve's surname?",- "Where does Eve live?",- "What color are Eve's eyes?",- "What school did Eve graduate from?",- "What dance styles does Eve specialize in?",- "What company does she work for?",- "What is her hobby besides dancing?",- "What is her cat's name?",- "What is Eve's height?",- "How much does she earn per year?",- "What is her favorite ballet?",- "Where does she volunteer?",- "What car does she drive?",- ];-- use std::time::Instant;-- let start_cached = Instant::now();- let context = build_context(&mut session, system_prompt);-- let cached_answers: Vec<String> = questions- .iter()- .map(|q| ask_with_context(&mut session, Some(context.clone()), q))- .collect();- let duration_cached = start_cached.elapsed().as_secs_f64();-- let start_plain = Instant::now();- let plain_answers: Vec<String> = questions- .iter()- .map(|q| {- let prompt = format!("{} {}", system_prompt, q);- ask_without_context(&mut session, &prompt)- })- .collect();- let duration_plain = start_plain.elapsed().as_secs_f64();-- println!(- "Plain answers: {:?}",- plain_answers- .iter()- .map(|a| a- .trim()- .replace("<think>", "")- .replace("</think>", "")- .replace("\n", " "))- .collect::<Vec<String>>()- );- println!(- "Cached answers: {:?}",- cached_answers- .iter()- .map(|a| a- .trim()- .replace("<think>", "")- .replace("</think>", "")- .replace("\n", " "))- .collect::<Vec<String>>()- );- println!("Plain duration ({} q): {:.3}s", questions.len(), duration_plain);- println!(- "Cached duration ({} q): {:.3}s",- questions.len(),- duration_cached- );-- assert!(duration_cached <= duration_plain);-}--fn create_session() -> Session {- let session = Session::new(model_path(), DecodingConfig::default())- .expect("Failed to load session");- session-}--fn build_context(- session: &mut Session,- prompt: &str,-) -> Rc<Context> {- // Run the prompt once to build the context.- let (_, context) = session- .extend(- Input::Text(prompt.to_string()),- None,- RunConfig::new(- 1,- true,- SamplingPolicy::Custom {- value: SamplingMethod::Greedy,- },- ),- )- .unwrap();- Rc::new(context)-}--fn ask_with_context(- session: &mut Session,- context: Option<Rc<Context>>,- question: &str,-) -> String {- session- .run_with_context(- Input::Text(format!("{} /no_think", question)),- context.as_deref(),- RunConfig::new(- 96,- true,- SamplingPolicy::Custom {- value: SamplingMethod::Greedy,- },- ),- )- .unwrap()- .text- .original-}--fn ask_without_context(- session: &mut Session,- question: &str,-) -> String {- session- .run(- Input::Text(format!("{} /no_think", question)),- RunConfig::new(- 96,- true,- SamplingPolicy::Custom {- value: SamplingMethod::Greedy,- },- ),- None::<fn(Output) -> bool>,- )- .unwrap()- .text- .original-}diff --git a/crates/uzu/tests/context_mode_test.rs b/crates/uzu/tests/context_mode_test.rsnew file mode 100644index 000000000..b8b63029f--- /dev/null+++ b/crates/uzu/tests/context_mode_test.rs@@ -0,0 +1,208 @@+mod common;+use std::path::PathBuf;++use uzu::session::{+ Session,+ config::{DecodingConfig, RunConfig, SpeculatorConfig},+ parameter::{+ ContextLength, ContextMode, PrefillStepSize, SamplingMethod,+ SamplingPolicy, SamplingSeed,+ },+ types::{Input, Message, Output},+};++fn build_model_path() -> PathBuf {+ common::get_test_model_path()+}++fn build_decoding_config() -> DecodingConfig {+ DecodingConfig::new(+ ContextMode::default(),+ ContextLength::default(),+ PrefillStepSize::default(),+ SpeculatorConfig::default(),+ SamplingSeed::Custom(42),+ true,+ )+}++fn request(+ session: &mut Session,+ input_text: String,+ tokens_limit: u64,+) -> String {+ session+ .run(+ Input::Text(input_text.clone()),+ RunConfig::new(+ tokens_limit,+ false,+ SamplingPolicy::Custom {+ value: SamplingMethod::Greedy,+ },+ ),+ None::<fn(Output) -> bool>,+ )+ .unwrap()+ .text+ .original+ .trim()+ .to_string()+}++#[test]+fn test_context_mode_none() {+ let decoding_config =+ build_decoding_config().with_context_mode(ContextMode::None);+ let mut session =+ Session::new(build_model_path(), decoding_config).unwrap();++ let tokens_limit = 48;+ let input_text = "What is Alice's occupation?".to_string();+ let response_1 = request(&mut session, input_text.clone(), tokens_limit);+ let response_2 = request(&mut session, input_text.clone(), tokens_limit);++ println!("response_1: {}", response_1);+ println!("response_2: {}", response_2);++ assert_eq!(response_1, response_2);+}++#[test]+fn test_context_mode_static() {+ let parameter_name = "Alice".to_string();+ let parameter_age = "30".to_string();+ let parameter_occupation = "Engineer".to_string();+ let parameter_city = "London".to_string();++ let decoding_config =+ build_decoding_config().with_context_mode(ContextMode::Static {+ input: Input::Messages(vec![+ Message::system(+ "Always answer with one word or number, no punctuation"+ .to_string(),+ ),+ Message::user(+ format!(+ "Name: {}\nAge: {}\nOccupation: {}\nCity: {}",+ parameter_name,+ parameter_age,+ parameter_occupation,+ parameter_city+ )+ .to_string(),+ ),+ ]),+ });+ let mut session =+ Session::new(build_model_path(), decoding_config).unwrap();++ let tokens_limit = 48;+ let response_occupation = request(+ &mut session,+ format!("What is {}'s occupation?", parameter_name),+ tokens_limit,+ );+ let response_age = request(+ &mut session,+ format!("What is {}'s age?", parameter_name),+ tokens_limit,+ );+ let response_city = request(+ &mut session,+ format!("What is {}'s city?", parameter_name),+ tokens_limit,+ );++ println!("Occupation: {}", response_occupation);+ println!("Age: {}", response_age);+ println!("City: {}", response_city);++ assert!(+ response_occupation+ .to_lowercase()+ .contains(parameter_occupation.to_lowercase().as_str())+ );+ assert!(+ response_age+ .to_lowercase()+ .contains(parameter_age.to_lowercase().as_str())+ );+ assert!(+ response_city+ .to_lowercase()+ .contains(parameter_city.to_lowercase().as_str())+ );+}++#[test]+fn test_context_mode_dynamic() {+ let decoding_config =+ build_decoding_config().with_context_mode(ContextMode::Dynamic);+ let mut session =+ Session::new(build_model_path(), decoding_config).unwrap();++ let update = |session: &mut Session, input_text: String| {+ request(session, input_text, 0)+ };+ let ask = |session: &mut Session, input_text: String| {+ request(session, input_text, 48)+ };++ update(&mut session, "Name: Dave. Occupation: Nurse. Age: 30.".to_string());+ let answer_1 = ask(&mut session, "What is Dave's occupation?".to_string());+ println!("Answer 1: {}", answer_1);+ assert!(answer_1.to_lowercase().contains("nurse"));++ update(+ &mut session,+ "Update: Name: Dave. Occupation: Doctor. Age: 30.".to_string(),+ );+ let answer_2 = ask(&mut session, "What is Dave's occupation?".to_string());+ println!("Answer 2: {}", answer_2);+ assert!(answer_2.to_lowercase().contains("doctor"));++ update(+ &mut session,+ "Update: Name: Dave. Occupation: Doctor. Age: 31.".to_string(),+ );+ let answer_3 = ask(&mut session, "How old is Dave?".to_string());+ println!("Answer 3: {}", answer_3);+ assert!(answer_3.to_lowercase().contains("31"));++ update(+ &mut session,+ "Important update, Dave got promoted! Update: Name: Dave. Occupation: Director. Age: 32.".to_string(),+ );+ let answer_4 =+ ask(&mut session, "What is Dave's current occupation?".to_string());+ println!("Answer 4: {}", answer_4);+ assert!(answer_4.to_lowercase().contains("director"));++ let answer_5 = ask(+ &mut session,+ "At what age did the last promotion occur?".to_string(),+ );+ println!("Answer 5: {}", answer_5);+ assert!(answer_5.to_lowercase().contains("32"));+}++#[test]+fn test_context_mode_dynamic_scenario() {+ let decoding_config =+ build_decoding_config().with_context_mode(ContextMode::Dynamic);+ let mut session =+ Session::new(build_model_path(), decoding_config).unwrap();++ let user_prompts = vec![+ String::from("Tell about London"),+ String::from("Compare with New York"),+ ];++ println!("-------------------------");+ for user_prompt in user_prompts {+ let answer = request(&mut session, user_prompt.clone(), 1024);+ println!("{} -> {}", user_prompt, answer);+ println!("-------------------------");+ }+}diff --git a/crates/uzu/tests/text_session_test.rs b/crates/uzu/tests/text_session_test.rsindex 6fafb2aaa..3a0d4c24b 100644--- a/crates/uzu/tests/text_session_test.rs+++ b/crates/uzu/tests/text_session_test.rs@@ -5,8 +5,8 @@ use uzu::session::{Session,config::{DecodingConfig, RunConfig, SpeculatorConfig},parameter::{- ContextLength, PrefillStepSize, SamplingMethod, SamplingPolicy,- SamplingSeed,+ ContextLength, ContextMode, PrefillStepSize, SamplingMethod,+ SamplingPolicy, SamplingSeed,},types::{Input, Message, Output},};@@ -17,8 +17,9 @@ fn build_model_path() -> PathBuf {fn build_decoding_config() -> DecodingConfig {DecodingConfig::new(- PrefillStepSize::default(),+ ContextMode::default(),ContextLength::default(),+ PrefillStepSize::default(),SpeculatorConfig::default(),SamplingSeed::Custom(42),true,