A high-performance inference engine for AI models
Session context
LuckyIYIa9931c82f1d3
diff --git a/README.md b/README.mdindex 8dd50f1a3..39e4e58e7 100644--- a/README.md+++ b/README.md@@ -104,7 +104,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {let output = session.run(input, run_config, Some(|_: SessionOutput| {return true;- }));+ }))?;println!("{}", output.text);Ok(())}diff --git a/cli/src/handlers/run.rs b/cli/src/handlers/run.rsindex aa08fc64e..147afc884 100644--- a/cli/src/handlers/run.rs+++ b/cli/src/handlers/run.rs@@ -89,11 +89,19 @@ pub fn handle_run(return true;};- let session_output = session.run(+ let session_output = match session.run(SessionInput::Text(input.to_string()),SessionRunConfig::new(tokens_limit as u64),Some(session_progress),- );+ ) {+ Ok(output) => output,+ Err(e) => {+ progress_bar.finish_and_clear();+ eprintln!("β Error during session run: {}", e);+ is_model_running.store(false, Ordering::SeqCst);+ return;+ },+ };let result = format_output(session_output);progress_bar.set_style(diff --git a/cli/src/server/chat_completions.rs b/cli/src/server/chat_completions.rsindex 7fc31bc52..0cd8599be 100644--- a/cli/src/server/chat_completions.rs+++ b/cli/src/server/chat_completions.rs@@ -1,48 +1,67 @@-use rocket::{post, serde::json::Json};+use std::{+ rc::Rc,+ time::{SystemTime, UNIX_EPOCH},+};++use rocket::{State, post, serde::json::Json};use serde::{Deserialize, Serialize};use uuid::Uuid;use uzu::session::{session_input::SessionInput,session_message::{SessionMessage, SessionMessageRole},session_output::{- SessionOutput, SessionOutputFinishReason, SessionOutputStats,+ SessionOutput, SessionOutputFinishReason, SessionOutputRunStats,+ SessionOutputStats, SessionOutputStepStats, SessionOutputTotalStats,},session_run_config::SessionRunConfig,};use crate::server::SessionState;-#[derive(Deserialize)]-pub struct ChatCompletionsRequest {- messages: Vec<SessionMessage>,- max_completion_tokens: Option<usize>,+#[derive(Serialize, Deserialize, Clone)]+pub struct ChatMessage {+ pub content: String,+ pub role: SessionMessageRole,+}++#[derive(Serialize, Deserialize)]+pub struct ChatCompletionRequest {+ pub messages: Vec<ChatMessage>,+ pub model: String,+ pub max_tokens: Option<u64>,+ pub system_prompt_key: Option<String>,}-#[derive(Serialize)]-pub struct ChatCompletionsResponseChoice {- index: usize,- message: SessionMessage,- finish_reason: SessionOutputFinishReason,+#[derive(Serialize, Deserialize, Clone)]+pub struct ChatCompletionChoice {+ pub index: u32,+ pub message: ChatMessage,+ pub finish_reason: String,}-#[derive(Serialize)]-pub struct ChatCompletionsResponse {- id: String,- model: String,- choices: Vec<ChatCompletionsResponseChoice>,- stats: SessionOutputStats,+#[derive(Serialize, Deserialize, Clone)]+pub struct ChatCompletionResponse {+ pub id: String,+ pub object: String,+ pub created: i64,+ pub model: String,+ pub choices: Vec<ChatCompletionChoice>,+ pub stats: SessionOutputStats,}-#[post("/chat/completions", data = "<request>")]+#[post("/chat/completions", format = "json", data = "<request>")]pub fn handle_chat_completions(- request: Json<ChatCompletionsRequest>,- state: &rocket::State<SessionState>,-) -> Json<ChatCompletionsResponse> {+ request: Json<ChatCompletionRequest>,+ state: &State<SessionState>,+) -> Json<ChatCompletionResponse> {+ let request = request.into_inner();let id = Uuid::new_v4().to_string();println!("π¨ [{}] Incoming chat completion request:", id);println!(" Messages: {} message(s)", request.messages.len());- println!(" Max tokens: {}", request.max_completion_tokens.unwrap_or(512));+ println!(" Max tokens: {}", request.max_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 {format!("{}...", &msg.content[..10000])@@ -52,19 +71,123 @@ pub fn handle_chat_completions(println!(" Message {}: {:?} - {}", i + 1, msg.role, content_preview);}- let tokens_limit = request.max_completion_tokens.unwrap_or(512) as u64;- let input = SessionInput::Messages(request.messages.clone());+ let model_name = state.model_name.clone();+ let system_prompt_key = request.system_prompt_key;+ let tokens_limit = request.max_tokens.unwrap_or(2048);+ let messages: Vec<SessionMessage> = request+ .messages+ .into_iter()+ .map(|m| SessionMessage {+ content: m.content,+ role: m.role,+ })+ .collect();+ let input = SessionInput::Messages(messages);let run_config = SessionRunConfig::new(tokens_limit);let start_time = std::time::Instant::now();let mut session = state.session_wrapper.lock();- let output = session.run(- input,- run_config,- Some(|_: SessionOutput| {- return true;- }),- );++ 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: SessionMessageRole::Assistant,+ },+ finish_reason: "error".to_string(),+ }],+ stats: SessionOutputStats {+ prefill_stats: SessionOutputStepStats {+ duration: 0.0,+ suffix_length: 0,+ tokens_count: 0,+ tokens_per_second: 0.0,+ model_run: SessionOutputRunStats {+ count: 0,+ average_duration: 0.0,+ },+ run: None,+ },+ generate_stats: None,+ total_stats: SessionOutputTotalStats {+ 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) {+ Ok(output) => output,+ Err(e) => {+ eprintln!("β [{}] Session run 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: SessionMessageRole::Assistant,+ },+ finish_reason: "error".to_string(),+ }],+ stats: SessionOutputStats {+ prefill_stats: SessionOutputStepStats {+ duration: 0.0,+ suffix_length: 0,+ tokens_count: 0,+ tokens_per_second: 0.0,+ model_run: SessionOutputRunStats {+ count: 0,+ average_duration: 0.0,+ },+ run: None,+ },+ generate_stats: None,+ total_stats: SessionOutputTotalStats {+ duration: 0.0,+ tokens_count_input: 0,+ tokens_count_output: 0,+ },+ },+ };+ return Json(error_response);+ },+ }+ };+let processing_time = start_time.elapsed();println!("output: {:?}", &output);@@ -101,19 +224,20 @@ pub fn handle_chat_completions(}println!();- let choice = ChatCompletionsResponseChoice {- index: 0,- message: SessionMessage {- role: SessionMessageRole::Assistant,- content: text,- },- finish_reason: finish_reason_val,- };-- let response = ChatCompletionsResponse {+ let response = ChatCompletionResponse {id: id.clone(),- model: state.model_name.clone(),- choices: vec![choice],+ object: "chat.completion".to_string(),+ created: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()+ as i64,+ model: model_name,+ choices: vec![ChatCompletionChoice {+ index: 0,+ message: ChatMessage {+ content: text,+ role: SessionMessageRole::Assistant,+ },+ finish_reason: format!("{:?}", finish_reason_val).to_lowercase(),+ }],stats,};diff --git a/cli/src/server/main.rs b/cli/src/server/main.rsindex 356109563..524a3aed7 100644--- a/cli/src/server/main.rs+++ b/cli/src/server/main.rs@@ -5,6 +5,7 @@ use rocket::{Config, config::LogLevel, log::private as log, routes};use crate::server::{SessionState, SessionWrapper, handle_chat_completions, load_session,+ state::ContextCache,};struct SilentLogger;@@ -57,6 +58,7 @@ 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/cli/src/server/state.rs b/cli/src/server/state.rsindex 30ca47220..c88f1db23 100644--- a/cli/src/server/state.rs+++ b/cli/src/server/state.rs@@ -1,8 +1,60 @@-use std::{path::PathBuf, sync::Mutex};+use std::{+ collections::{HashMap, VecDeque},+ path::PathBuf,+ rc::Rc,+ sync::Mutex,+};use console::Style;use indicatif::{ProgressBar, ProgressStyle};-use uzu::session::{session::Session, session_config::SessionConfig};+use uzu::session::{+ session::Session, session_config::SessionConfig,+ session_context::SessionContext,+};++pub struct ContextCache {+ pub map: HashMap<String, Rc<SessionContext>>,+ 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<SessionContext>,+ ) -> Option<(String, Rc<SessionContext>)> {+ 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<SessionContext>> {+ self.map.get(key).cloned()+ }+}pub struct SessionWrapper(Mutex<Session>);unsafe impl Send for SessionWrapper {}@@ -20,8 +72,12 @@ impl SessionWrapper {pub struct SessionState {pub model_name: String,pub session_wrapper: SessionWrapper,+ pub cache: Mutex<ContextCache>,}+unsafe impl Send for SessionState {}+unsafe impl Sync for SessionState {}+pub fn load_session(model_path: String) -> Session {let style_bold = Style::new().bold();@@ -43,6 +99,7 @@ pub fn load_session(model_path: String) -> Session {let mut session =Session::new(model_path_buf).expect("Failed to create session");+session.load_with_session_config(SessionConfig::default()).expect("Failed to load session");diff --git a/uzu/src/backends/metal/array.rs b/uzu/src/backends/metal/array.rsindex 66e96720c..99986a037 100644--- a/uzu/src/backends/metal/array.rs+++ b/uzu/src/backends/metal/array.rs@@ -1,3 +1,5 @@+use std::ops::Range;+use half::{bf16, f16};use metal::{Buffer as MTLBuffer, MTLResourceOptions};use mpsgraph::TensorData;@@ -195,4 +197,60 @@ impl MetalArray {.unwrap().copy_from_slice(array.as_slice::<T>().unwrap());}++ pub fn copy_slice(+ &mut self,+ source: &Self,+ axis: usize,+ src_range: Range<usize>,+ dst_offset: usize,+ ) {+ assert_eq!(self.shape().len(), source.shape().len(), "Rank mismatch");+ assert!(axis < self.shape().len(), "Axis out of bounds");+ for (i, (a, b)) in self.shape().iter().zip(source.shape()).enumerate() {+ if i != axis {+ assert_eq!(a, b, "Shapes must match on all non-sliced axes");+ }+ }+ assert_eq!(+ self.data_type(),+ source.data_type(),+ "Arrays must have the same data type"+ );++ let elem_size = self.data_type().size_in_bytes();++ // The number of contiguous elements to copy for each slice operation+ let block_size_elems =+ self.shape().iter().skip(axis + 1).product::<usize>();+ let block_size_bytes = block_size_elems * elem_size;++ // The total number of blocks to copy+ let num_blocks: usize = self.shape().iter().take(axis).product();++ // Strides between the start of each block+ let src_stride_bytes = source.shape()[axis] * block_size_bytes;+ let dst_stride_bytes = self.shape()[axis] * block_size_bytes;++ let rows_to_copy = src_range.end - src_range.start;+ assert!(dst_offset + rows_to_copy <= self.shape()[axis]);+ assert!(src_range.end <= source.shape()[axis]);++ let src_buf = source.buffer();+ let dst_buf = self.buffer_mut();+ let copy_bytes = rows_to_copy * block_size_bytes;++ for i in 0..num_blocks {+ let src_block_start = i * src_stride_bytes;+ let dst_block_start = i * dst_stride_bytes;++ let src_start =+ src_block_start + src_range.start * block_size_bytes;+ let dst_start = dst_block_start + dst_offset * block_size_bytes;++ let src_slice = &src_buf[src_start..src_start + copy_bytes];+ let dst_slice = &mut dst_buf[dst_start..dst_start + copy_bytes];+ dst_slice.copy_from_slice(src_slice);+ }+ }}diff --git a/uzu/src/backends/metal/forward_pass/encodable_with_state.rs b/uzu/src/backends/metal/forward_pass/encodable_with_state.rsindex 5acdb759b..9a602adb2 100644--- a/uzu/src/backends/metal/forward_pass/encodable_with_state.rs+++ b/uzu/src/backends/metal/forward_pass/encodable_with_state.rs@@ -23,7 +23,10 @@ impl EncodingParameters {}}- pub fn with_projection(mut self, projection_step: usize) -> Self {+ pub fn with_projection(+ mut self,+ projection_step: usize,+ ) -> Self {self.projection_step = Some(projection_step);self}diff --git a/uzu/src/backends/metal/forward_pass/kv_cache.rs b/uzu/src/backends/metal/forward_pass/kv_cache.rsindex c2534e6a7..4320a5fbd 100644--- a/uzu/src/backends/metal/forward_pass/kv_cache.rs+++ b/uzu/src/backends/metal/forward_pass/kv_cache.rs@@ -7,12 +7,14 @@ use super::{model_shape::ModelShape,};use crate::{- Array, DeviceContext,+ DeviceContext,+ array::Array,backends::metal::kernel::{KVCacheUpdate, kv_cache_update::KVLayerData},};type ArrayCell = RefCell<MetalArray>;+#[derive(Clone, Debug)]pub enum KVCacheLayerState {Full {// Prefix length so far (number of tokens in the prefix)@@ -448,4 +450,62 @@ impl KVCache {layer.register_accepted_tokens(token_positions);}}++ pub fn clone_with_prefix_len(+ &self,+ context: &MTLContext,+ prefix_len: usize,+ ) -> Self {+ let new_total_len = prefix_len + self.max_suffix_length;+ let data: Box<[KVCacheLayer]> = self+ .data+ .iter()+ .map(|layer| {+ let shape = layer.keys.borrow().shape().to_vec();+ 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 mut new_keys = context.array(&new_shape, dtype);+ let mut new_values = context.array(&new_shape, dtype);++ let mut copy_rows = layer.effective_prefix_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(),+ 1,+ 0..copy_rows,+ 0,+ );+ new_values.copy_slice(+ &layer.values.borrow(),+ 1,+ 0..copy_rows,+ 0,+ );+ }++ KVCacheLayer {+ state: layer.state.clone(),+ keys: RefCell::new(new_keys),+ values: RefCell::new(new_values),+ prefix_token_positions: layer+ .prefix_token_positions+ .clone(),+ max_suffix_length: layer.max_suffix_length,+ }+ })+ .collect();++ Self {+ max_suffix_length: self.max_suffix_length,+ max_prefix_length: prefix_len,+ data,+ }+ }}diff --git a/uzu/src/backends/metal/forward_pass/mod.rs b/uzu/src/backends/metal/forward_pass/mod.rsindex 8e47d87d8..854fcbc28 100644--- a/uzu/src/backends/metal/forward_pass/mod.rs+++ b/uzu/src/backends/metal/forward_pass/mod.rs@@ -1,12 +1,12 @@mod buffers;pub mod encodable_with_state;mod io_arrays;+pub mod kv_cache;mod model_shape;mod mpsgraph_block;mod state;pub mod traces;pub mod transformer_layer;-pub mod kv_cache;pub use buffers::ForwardPassBuffers;pub use io_arrays::IOArrays;diff --git a/uzu/src/backends/metal/kernel/attention/mod.rs b/uzu/src/backends/metal/kernel/attention/mod.rsindex f26af2765..077d34034 100644--- a/uzu/src/backends/metal/kernel/attention/mod.rs+++ b/uzu/src/backends/metal/kernel/attention/mod.rs@@ -575,7 +575,10 @@ impl EncodableWithState for AttentionKernelEncodable {)};- let prefix_length = state.kv_cache.borrow().data[self.layer_index].projected_effective_prefix_length(parameters.projection_step.unwrap_or(0));+ let prefix_length = state.kv_cache.borrow().data[self.layer_index]+ .projected_effective_prefix_length(+ parameters.projection_step.unwrap_or(0),+ );let sequence_length = prefix_length + suffix_length;let window_length =diff --git a/uzu/src/generator/config.rs b/uzu/src/generator/config.rsindex 0b57576e5..15756770e 100644--- a/uzu/src/generator/config.rs+++ b/uzu/src/generator/config.rs@@ -73,6 +73,7 @@ pub trait GeneratorConfigProvider {) -> GeneratorConfig;}+#[derive(Clone)]pub struct GeneratorConfig {pub prefill_step_size: usize,pub speculator_config: SpeculatorConfig,diff --git a/uzu/src/generator/context.rs b/uzu/src/generator/context.rsindex f4ad3c1f8..8101dec46 100644--- a/uzu/src/generator/context.rs+++ b/uzu/src/generator/context.rs@@ -110,7 +110,7 @@ impl GeneratorContext {let intermediate_data_type: DataType =decoder_config.output_norm_config.scale_precision.into();let kernel_data_type: KernelDataType = intermediate_data_type.into();- let kv_cache_update: Box<KVCacheUpdate> = Box::new(+ let kv_cache_update = Box::new(KVCacheUpdate::new(&mtl_context,kernel_data_type,diff --git a/uzu/src/generator/generator.rs b/uzu/src/generator/generator.rsindex bf10b80cb..fa050941a 100644--- a/uzu/src/generator/generator.rs+++ b/uzu/src/generator/generator.rs@@ -11,8 +11,8 @@ use super::{use crate::{Array,backends::metal::{- ForwardPassState,forward_pass::{+ ForwardPassState,encodable_with_state::{EncodableWithState, EncodingParameters},kv_cache::INVALID_POSITION,},@@ -27,7 +27,7 @@ pub struct Generator {pub config: GeneratorConfig,pub tokens: Vec<u64>,- context: GeneratorContext,+ pub context: GeneratorContext,encoded_tasks: HashMap<String, GeneratorEncodedTask>,registered_prefix_len: usize,}@@ -61,11 +61,11 @@ impl Generator {&mut self,tokens: Vec<u64>,sampling_config: SamplingConfig,+ prefix_offset: usize,) -> PrefillResult {assert!(!tokens.is_empty());- self.context.kv_cache.borrow_mut().clear();- self.tokens = tokens.clone();+ self.tokens.extend(tokens.clone());let tokens_length = tokens.len();let number_of_prefill_steps = (tokens_length as f32@@ -90,21 +90,23 @@ impl Generator {].concat();- let mut padded_positions: Vec<usize> = (0..tokens_length).collect();+ let mut padded_positions: Vec<usize> =+ (prefix_offset..prefix_offset + tokens_length).collect();padded_positions.extend(- speculated_suffix.indices.iter().map(|index| index + tokens_length),+ speculated_suffix+ .indices+ .iter()+ .map(|index| index + prefix_offset + tokens_length),);let padding_count =unused_tokens_count - speculated_suffix.tokens.len();- let zero_padding_indicies: Vec<usize> =- vec![INVALID_POSITION; padding_count];-- padded_positions.extend(zero_padding_indicies);+ padded_positions+ .extend(std::iter::repeat(INVALID_POSITION).take(padding_count));let mut last_state: Option<ForwardPassState> = None;let mut run_times: Vec<f64> = Vec::new();- // Process each prefill step and update KV cache immediately+ // Process each prefill step and update the KV cache.for step in 0..number_of_prefill_steps {let tokens_start_index = step * self.config.prefill_step_size;let tokens_end_index =@@ -115,7 +117,6 @@ impl Generator {&padded_positions[tokens_start_index..tokens_end_index];objc2::rc::autoreleasepool(|_pool| {- // Drop previous state to release any transient Metal objectslet _ = last_state.take();});@@ -132,16 +133,20 @@ impl Generator {Some(sampling_config.clone()),);- // Register tokens with KV cache immediately after each step+ // Register the *accepted* real tokens from this step (exclude the+ // padding token at the very end of the overall prefill).let step_end_token_index =std::cmp::min(tokens_end_index, tokens_length);let tokens_processed_this_step =step_end_token_index - tokens_start_index;if tokens_processed_this_step > 0 {- let mut positions_for_step: Vec<usize> =- (tokens_start_index..step_end_token_index).collect();+ let mut positions_for_step: Vec<usize> = (tokens_start_index+ ..step_end_token_index)+ .map(|idx| idx + prefix_offset)+ .collect();if step == number_of_prefill_steps - 1 {+ // Exclude the last token because it belongs to the suffix for sampling.positions_for_step.pop();}@@ -161,7 +166,6 @@ impl Generator {}let mut final_state = last_state.unwrap();-let argmax_tokens = self.gpu_sample(&mut final_state);let mut accepted_token_indices: Vec<usize> = Vec::new();@@ -172,7 +176,6 @@ impl Generator {+ tokens_length as isize)% self.config.prefill_step_size as isize)as usize;-let new_token = argmax_tokens[current_index_in_window];accepted_tokens.push(new_token);@@ -193,6 +196,7 @@ impl Generator {self.update_kv_cache(&mut final_state, &accepted_token_indices);self.tokens.extend(accepted_tokens.clone());+self.sync_prefix();PrefillResult {@@ -290,6 +294,17 @@ impl Generator {});}+ pub fn reset_state(&mut self) {+ self.context.kv_cache.borrow_mut().clear();+ self.tokens.clear();+ self.registered_prefix_len = 0;+ self.encoded_tasks.clear();+ }++ pub fn prefix_len(&self) -> usize {+ self.registered_prefix_len+ }+fn warmup(&mut self,suffix_length: usize,diff --git a/uzu/src/lib.rs b/uzu/src/lib.rsindex fd4bd79c2..f7ef73d28 100644--- a/uzu/src/lib.rs+++ b/uzu/src/lib.rs@@ -3,10 +3,10 @@ pub mod backends;pub mod config;pub mod data_type;pub use data_type::{ArrayElement, DataType};+pub mod decoder_runner;pub mod device_context;pub use array::Array;pub use device_context::DeviceContext;-pub mod decoder_runner;pub mod env_utils;pub mod generator;pub mod linearizer;diff --git a/uzu/src/session/mod.rs b/uzu/src/session/mod.rsindex 13ba501f1..36048a080 100644--- a/uzu/src/session/mod.rs+++ b/uzu/src/session/mod.rs@@ -8,3 +8,6 @@ pub mod session_message;pub mod session_output;pub mod session_run_config;pub mod session_tokenizer_config;+pub use session_context::*;++pub mod session_context;diff --git a/uzu/src/session/session.rs b/uzu/src/session/session.rsindex fc0b422ed..d8d4ee61a 100644--- a/uzu/src/session/session.rs+++ b/uzu/src/session/session.rs@@ -1,13 +1,11 @@-use std::{- path::{Path, PathBuf},- time::Instant,-};+use std::{path::PathBuf, time::Instant};use objc2::rc::autoreleasepool;use tokenizers::Tokenizer;use super::{session_config::SessionConfig,+ session_context::SessionContext,session_input::{SessionInput, SessionInputProcessor, SessionInputProcessorDefault,},@@ -118,15 +116,74 @@ impl Session {self.load(Box::new(config))}+ pub fn extend(+ &mut self,+ input: SessionInput,+ context: Option<&SessionContext>,+ config: SessionRunConfig,+ ) -> Result<(SessionOutput, SessionContext), SessionError> {+ self.reconfigure_generator(context)?;+ let output = self.run_internal(+ input,+ config,+ None::<fn(SessionOutput) -> bool>,+ )?;+ let new_context = self.build_context_from_generator()?;+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+ generator.reset_state();+ Ok((output, new_context))+ }+pub fn run<F>(&mut self,input: SessionInput,config: SessionRunConfig,progress: Option<F>,- ) -> SessionOutput+ ) -> Result<SessionOutput, SessionError>whereF: Fn(SessionOutput) -> bool,{+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+ generator.reset_state();+ let output = self.run_internal(input, config, progress)?;+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+ generator.reset_state();+ Ok(output)+ }++ pub fn run_with_context(+ &mut self,+ input: SessionInput,+ context: Option<&SessionContext>,+ config: SessionRunConfig,+ ) -> Result<SessionOutput, SessionError> {+ self.reconfigure_generator(context)?;+ let output = self.run_internal(+ input,+ config,+ None::<fn(SessionOutput) -> bool>,+ )?;+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+ generator.reset_state();+ Ok(output)+ }++ fn run_internal<F>(+ &mut self,+ input: SessionInput,+ config: SessionRunConfig,+ progress: Option<F>,+ ) -> Result<SessionOutput, SessionError>+ where+ F: Fn(SessionOutput) -> bool,+ {+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+let run_start = Instant::now();let text = self.input_processor.process(&input);let tokens: Vec<u64> = self@@ -138,6 +195,8 @@ impl Session {.map(|&id| id as u64).collect();+ let prefix_len_before = generator.prefix_len();+let eos_tokens = self.tokenizer_config.eos_tokens@@ -146,10 +205,12 @@ impl Session {self.tokenizer.token_to_id(token.as_str()).unwrap() as u64}).collect::<Vec<_>>();+let finish_reason = |generator: &Generator,tokens_new: Vec<u64>|-> Option<SessionOutputFinishReason> {- let total_new_tokens = generator.tokens[tokens.len()..].len();+ let start_idx = prefix_len_before + tokens.len();+ let total_new_tokens = generator.tokens[start_idx..].len();let has_eos_token =tokens_new.iter().any(|token| eos_tokens.contains(token));@@ -161,26 +222,27 @@ impl Session {None}};- let build_generated_text = |generator: &Generator,- tokenizer: &Tokenizer|- -> String {- let generated_tokens: Vec<u32> = generator.tokens[tokens.len()..]- .to_vec()- .iter()- .map(|value| *value as u32)- .collect();- let generated_text =- tokenizer.decode(&generated_tokens, true).unwrap();- generated_text- };- let generator = self.generator.as_mut().unwrap();+ let build_generated_text =+ |generator: &Generator, tokenizer: &Tokenizer| -> String {+ let start_idx = prefix_len_before + tokens.len();+ let generated_tokens: Vec<u32> = generator.tokens[start_idx..]+ .to_vec()+ .iter()+ .map(|value| *value as u32)+ .collect();+ tokenizer.decode(&generated_tokens, true).unwrap()+ };+let sampling_config = config.sampling_config.unwrap_or(self.tokenizer_config.sampling_config);let prefill_start = Instant::now();- let prefill_result = generator.prefill(tokens.clone(), sampling_config);+ let prefix_offset = generator.tokens.len();++ let prefill_result =+ generator.prefill(tokens.clone(), sampling_config, prefix_offset);let prefill_tokens = prefill_result.tokens.clone();let prefill_duration = prefill_start.elapsed().as_secs_f64();generator.clear_cache();@@ -189,6 +251,7 @@ impl Session {finish_reason(generator, prefill_tokens.clone());let prefill_generated_text =build_generated_text(generator, &self.tokenizer);+let prefill_output = SessionOutput {text: prefill_generated_text,stats: Self::build_stats(@@ -200,22 +263,24 @@ impl Session {generator.config.generate_suffix_length(),run_start.elapsed().as_secs_f64(),tokens.len(),- generator.tokens[tokens.len()..].len(),+ generator.tokens[prefix_len_before + tokens.len()..].len(),),finish_reason: prefill_finish_reason.clone(),};+let prefill_should_continue = if let Some(progress) = &progress {progress(prefill_output.clone())} else {true};+if !prefill_should_continue || prefill_finish_reason.is_some() {if prefill_should_continue {- return prefill_output;+ return Ok(prefill_output);} else {- return prefill_output.clone_with_finish_reason(Some(+ return Ok(prefill_output.clone_with_finish_reason(Some(SessionOutputFinishReason::Cancelled,- ));+ )));}}@@ -233,6 +298,7 @@ impl Session {finish_reason(generator, generate_tokens);let generate_generated_text =build_generated_text(generator, &self.tokenizer);+let generate_output = SessionOutput {text: generate_generated_text,stats: Self::build_stats(@@ -244,15 +310,17 @@ impl Session {generator.config.generate_suffix_length(),run_start.elapsed().as_secs_f64(),tokens.len(),- generator.tokens[tokens.len()..].len(),+ generator.tokens[prefix_len_before + tokens.len()..].len(),),finish_reason: generate_finish_reason.clone(),};+let generate_should_continue = if let Some(progress) = &progress {progress(generate_output.clone())} else {true};+if !generate_should_continue || generate_finish_reason.is_some() {if generate_should_continue {break generate_output;@@ -263,9 +331,67 @@ impl Session {}}};+generator.clear_cache();+ Ok(generate_output+ .clone_with_duration(run_start.elapsed().as_secs_f64()))+ }++ fn reconfigure_generator(+ &mut self,+ context: Option<&SessionContext>,+ ) -> Result<(), SessionError> {+ let generator =+ self.generator.as_mut().ok_or(SessionError::GeneratorNotLoaded)?;+ generator.reset_state();+ if let Some(ctx) = context {+ let mut generator_cache = generator.context.kv_cache.borrow_mut();+ for (ctx_layer, gen_layer) in+ ctx.kv_cache.data.iter().zip(generator_cache.data.iter_mut())+ {+ let copy_rows = ctx_layer.effective_prefix_length();+ if copy_rows > 0 {+ gen_layer.keys.borrow_mut().copy_slice(+ &ctx_layer.keys.borrow(),+ 1,+ 0..copy_rows,+ 0,+ );+ gen_layer.values.borrow_mut().copy_slice(+ &ctx_layer.values.borrow(),+ 1,+ 0..copy_rows,+ 0,+ );+ }+ gen_layer.state = ctx_layer.state.clone();+ gen_layer.prefix_token_positions =+ ctx_layer.prefix_token_positions.clone();+ }+ drop(generator_cache);++ generator.tokens = ctx.tokens.clone();+ }+ Ok(())+ }- generate_output.clone_with_duration(run_start.elapsed().as_secs_f64())+ fn build_context_from_generator(+ &self+ ) -> Result<SessionContext, SessionError> {+ let generator =+ self.generator.as_ref().ok_or(SessionError::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);+ let context = SessionContext::new(+ generator.tokens.clone(),+ kv_cache,+ generator.config.clone(),+ );+ Ok(context)}}diff --git a/uzu/src/session/session_context.rs b/uzu/src/session/session_context.rsnew file mode 100644index 000000000..57e838e40--- /dev/null+++ b/uzu/src/session/session_context.rs@@ -0,0 +1,24 @@+use crate::{+ backends::metal::forward_pass::kv_cache::KVCache,+ generator::config::GeneratorConfig,+};++pub struct SessionContext {+ pub tokens: Vec<u64>,+ pub kv_cache: KVCache,+ pub config: GeneratorConfig,+}++impl SessionContext {+ pub fn new(+ tokens: Vec<u64>,+ kv_cache: KVCache,+ config: GeneratorConfig,+ ) -> Self {+ Self {+ tokens,+ kv_cache,+ config,+ }+ }+}diff --git a/uzu/src/session/session_error.rs b/uzu/src/session/session_error.rsindex 8cdc3b05a..b00df81f4 100644--- a/uzu/src/session/session_error.rs+++ b/uzu/src/session/session_error.rs@@ -14,6 +14,8 @@ pub enum SessionError {UnableToLoadTokenizerConfig,#[error("Model is too large to fit into available RAM")]UnsupportedModel,+ #[error("Generator not loaded. Call load() first")]+ GeneratorNotLoaded,}impl From<GeneratorError> for SessionError {diff --git a/uzu/tests/attention_kernel_test.rs b/uzu/tests/attention_kernel_test.rsindex 7668c8614..eca876e62 100644--- a/uzu/tests/attention_kernel_test.rs+++ b/uzu/tests/attention_kernel_test.rs@@ -1069,4 +1069,4 @@ fn perf_two_pass_attention() {}println!("β Two-pass attention performance test completed");-}\ No newline at end of file+}diff --git a/uzu/tests/context_kv_cache_test.rs b/uzu/tests/context_kv_cache_test.rsnew file mode 100644index 000000000..e2ceb509f--- /dev/null+++ b/uzu/tests/context_kv_cache_test.rs@@ -0,0 +1,280 @@+use std::{path::PathBuf, rc::Rc};++use uzu::{+ backends::metal::sampling_config::SamplingConfig,+ session::{+ session::Session, session_config::SessionConfig,+ session_context::SessionContext, session_input::SessionInput,+ session_output::SessionOutput, session_run_config::SessionRunConfig,+ },+};++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(+ SessionInput::Text(+ "Update: Name: Dave. Occupation: Doctor.".to_string(),+ ),+ Some(initial_context.as_ref()),+ SessionRunConfig::new(1),+ )+ .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 mut session = Session::new(model_path()).unwrap();+ session+ .load_with_session_config(SessionConfig::default())+ .expect("Failed to load session");++ session+}++fn build_context(+ session: &mut Session,+ prompt: &str,+) -> Rc<SessionContext> {+ // Run the prompt once to build the context.+ let (_, context) = session+ .extend(+ SessionInput::Text(prompt.to_string()),+ None,+ SessionRunConfig::new(1),+ )+ .unwrap();+ Rc::new(context)+}++fn ask_with_context(+ session: &mut Session,+ context: Option<Rc<SessionContext>>,+ question: &str,+) -> String {+ session+ .run_with_context(+ SessionInput::Text(format!("{} /no_think", question)),+ context.as_deref(),+ SessionRunConfig::new_with_sampling_config(+ 96,+ Some(SamplingConfig::Argmax),+ ),+ )+ .unwrap()+ .text+}++fn ask_without_context(+ session: &mut Session,+ question: &str,+) -> String {+ session+ .run(+ SessionInput::Text(format!("{} /no_think", question)),+ SessionRunConfig::new_with_sampling_config(+ 96,+ Some(SamplingConfig::Argmax),+ ),+ None::<fn(SessionOutput) -> bool>,+ )+ .unwrap()+ .text+}diff --git a/uzu/tests/generator_test.rs b/uzu/tests/generator_test.rsindex afeefc9ec..8986f9365 100644--- a/uzu/tests/generator_test.rs+++ b/uzu/tests/generator_test.rs@@ -37,16 +37,18 @@ fn run(session.load_with_session_config(config).unwrap();let input = SessionInput::Text(text);- let output = session.run(- input,- SessionRunConfig::new_with_sampling_config(- tokens_limit,- Some(SamplingConfig::Argmax),- ),- Some(|_: SessionOutput| {- return true;- }),- );+ let output = session+ .run(+ input,+ SessionRunConfig::new_with_sampling_config(+ tokens_limit,+ Some(SamplingConfig::Argmax),+ ),+ Some(|_: SessionOutput| {+ return true;+ }),+ )+ .unwrap();println!("-------------------------");println!("{}", output.text);diff --git a/uzu/tests/safetensors_metadata_test.rs b/uzu/tests/safetensors_metadata_test.rsindex a877c7c63..60f5361f2 100644--- a/uzu/tests/safetensors_metadata_test.rs+++ b/uzu/tests/safetensors_metadata_test.rs@@ -9,4 +9,4 @@ fn test_metadata_loading() {let file = File::open(&path).expect("weights not found");let (_offset, metadata) = read_metadata(&file).expect("read metadata");assert!(metadata.tensors.len() > 0);-}\ No newline at end of file+}diff --git a/uzu/tests/tracer_test.rs b/uzu/tests/tracer_test.rsindex a88149fc3..8ce1a1e9b 100644--- a/uzu/tests/tracer_test.rs+++ b/uzu/tests/tracer_test.rs@@ -13,7 +13,10 @@ fn test_tracer() {// Ensure traces file present, otherwise skiplet traces_path = crate::common::get_traces_path();if !traces_path.exists() {- println!("Skipping tracer test: traces file missing at {:?}", traces_path);+ println!(+ "Skipping tracer test: traces file missing at {:?}",+ traces_path+ );return;}