//! The real engine: the gpt-oss decoder behind the [`Decoder`] trait. use crate::serve::Decoder; use crate::slots::{self, Choice, SlotView}; use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::mapping::Mapping; use leleka_gguf::Gguf; use leleka_gptoss::{Model, PrefillAccelerator, State}; use leleka_tokenizer::gguf_bpe::GgufBpe; use std::fs::File; use std::io::BufReader; use std::path::Path; use std::sync::Arc; use std::time::Instant; /// One conversation's cache: a decoder state and when it was last used. struct Slot { state: State, last_used: u64, } pub struct GptOssEngine { model: Model, /// Caches of up to `max_slots` conversations, created when first needed (see `crate::slots`). slots: Vec, max_slots: usize, /// The slot of the request being served. active: usize, clock: u64, /// Print the slot chosen for every prompt on standard error. log_slots: bool, context: usize, /// Optional prefill on other hardware, used when at least `accelerate_from` prompt tokens need /// computing. The CPU worker itself has none; the GPU worker installs one. accelerator: Option>, accelerate_from: usize, /// EXPERIMENTAL: exact speculative decoding from prompt lookup (see `leleka_gptoss::speculate`). speculate: bool, } impl GptOssEngine { /// Switch exact prompt-lookup speculative decoding on or off (off by default). pub fn set_speculation(&mut self, on: bool) { self.speculate = on; } /// Keep the caches of up to `slots` conversations (1 by default: only the last request's). A request continues /// the slot that holds its conversation, a new agent that shares a system prompt with a cached one gets a copy /// of the shared part, and the least recently used slot is overwritten when all are taken. Slots are created when /// needed; each costs `context * 49 KB` of memory once filled (about 0.8 GB at 16,384 tokens). pub fn set_cache_slots(&mut self, slots: usize) { self.max_slots = slots.clamp(1, 64); if self.slots.len() > self.max_slots { self.slots.truncate(self.max_slots); self.active = self.active.min(self.slots.len() - 1); } let per_slot = self.context as u64 * self.model.config.kv_width() as u64 * 4 * self.model.config.blocks as u64; eprintln!( "leleka-cpu-worker: {} cache slot(s) of {} tokens, {} MiB each once filled", self.max_slots, self.context, per_slot >> 20 ); } /// Forget every cached conversation (all slots start empty; used to start measurements cold). pub fn reset_cache(&mut self) { for slot in &mut self.slots { slot.state.truncate(0); slot.last_used = 0; } self.clock = 0; } /// Make `active` the slot to run `prompt` in, copying a shared prefix from another slot when that is better. fn select_slot(&mut self, prompt: &[u32]) { let views: Vec> = self .slots .iter() .map(|slot| SlotView { tokens: slot.state.cached_tokens(), last_used: slot.last_used, }) .collect(); let choice = slots::choose(&views, self.max_slots, prompt); drop(views); let target = self.apply_choice(choice); self.clock += 1; self.slots[target].last_used = self.clock; self.active = target; if self.log_slots { eprintln!( "leleka-cpu-worker: prompt of {} tokens: {choice:?}; slots hold {:?}", prompt.len(), self.slots .iter() .map(|slot| slot.state.cached_tokens().len()) .collect::>() ); } } /// Create the slot a choice names if it is new and copy the shared prefix when asked; returns the slot to run in. fn apply_choice(&mut self, choice: Choice) -> usize { let (config, context) = (&self.model.config, self.context); let ensure = |slots: &mut Vec, index: usize| { if index == slots.len() { slots.push(Slot { state: State::new(config, context), last_used: 0, }); } }; match choice { Choice::Continue { slot } => slot, Choice::Fresh { slot } => { ensure(&mut self.slots, slot); slot } Choice::Copy { from, into, len } => { ensure(&mut self.slots, into); let (donor, target) = if from < into { let (head, tail) = self.slots.split_at_mut(into); (&head[from], &mut tail[0]) } else { let (head, tail) = self.slots.split_at_mut(from); (&tail[0], &mut head[into]) }; target.state.copy_prefix_from(&donor.state, len); into } } } fn state(&self) -> &State { &self.slots[self.active].state } /// Run long prefills (at least `min_tokens` tokens to compute) on `accelerator`. If it fails, the /// request is redone on the CPU and the accelerator is dropped for the rest of the session. pub fn set_accelerator(&mut self, accelerator: Box, min_tokens: usize) { self.accelerator = Some(accelerator); self.accelerate_from = min_tokens; } } /// What loading found out, for the log and the stop tokens. pub struct Loaded { pub engine: GptOssEngine, /// Tokens that end a generation: the end-of-generation markers of the Harmony format. pub stop_tokens: Vec, } pub struct LoadOptions<'a> { pub model: &'a Path, pub threads: usize, pub context: usize, /// Read every page of the model file once at startup, so the first requests do not page it in. pub warm: bool, } pub fn load(options: &LoadOptions) -> Result { let size = std::fs::metadata(options.model) .map_err(|e| format!("cannot read the model file: {e}"))? .len(); let file = File::open(options.model).map_err(|e| format!("cannot open the model file: {e}"))?; let gguf = Gguf::read(BufReader::with_capacity(1 << 20, file), size).map_err(|e| format!("invalid GGUF: {e}"))?; let tokenizer = GgufBpe::from_gguf(&gguf).map_err(|e| e.to_string())?; let stop_tokens = stop_tokens_of(&tokenizer)?; let mapping = Mapping::open(options.model).map_err(|e| format!("cannot map the model: {e}"))?; if options.warm { let started = Instant::now(); let checksum = mapping.touch_pages(); eprintln!( "leleka-cpu-worker: read {} bytes of the model in {:.1} s (checksum {checksum})", mapping.len(), started.elapsed().as_secs_f64() ); } let dispatch = Dispatch::from_env().map_err(|e| format!("kernel level: {e}"))?; let model = Model::load(Arc::new(mapping), &gguf, dispatch, options.threads).map_err(|e| e.to_string())?; let context = options.context.min(model.config.context_length); let state = State::new(&model.config, context); eprintln!( "leleka-cpu-worker: gpt-oss loaded; kernels {}, {} threads, context {context}, stop tokens {stop_tokens:?}", dispatch.isa(), model.threads() ); Ok(Loaded { engine: GptOssEngine::with_one_slot(model, state, context), stop_tokens, }) } /// The end-of-generation markers of the Harmony format that the vocabulary has, then its end-of-sequence token. fn stop_tokens_of(tokenizer: &GgufBpe) -> Result, String> { let mut stop_tokens = Vec::new(); for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] { if let Some(id) = tokenizer.token_id(marker) { stop_tokens.push(id); } } if let Some(eos) = tokenizer.eos && !stop_tokens.contains(&eos) { stop_tokens.push(eos); } if stop_tokens.is_empty() { return Err("the vocabulary has no end-of-generation token".into()); } Ok(stop_tokens) } impl GptOssEngine { /// An engine with one cache slot holding `state`, no accelerator and no speculation. fn with_one_slot(model: Model, state: State, context: usize) -> Self { Self { model, slots: vec![Slot { state, last_used: 0 }], max_slots: 1, active: 0, clock: 0, log_slots: std::env::var_os("LELEKA_SLOT_LOG").is_some(), context, accelerator: None, accelerate_from: usize::MAX, speculate: false, } } } impl Decoder for GptOssEngine { fn max_context(&self) -> usize { self.context } fn prefill( &mut self, prompt: &[u32], progress: &mut dyn FnMut(usize, usize) -> bool, ) -> Result, String> { self.select_slot(prompt); let state = &mut self.slots[self.active].state; if let Some(accelerator) = self.accelerator.as_mut() { match self.model.prefill_reuse_accelerated( state, prompt, accelerator.as_mut(), self.accelerate_from, progress, ) { Ok(done) => return Ok(done.map(|r| r.reused)), Err(e) => { eprintln!( "leleka-cpu-worker: accelerated prefill failed ({e}); redoing it on the CPU and disabling the accelerator" ); self.accelerator = None; } } } self.model .prefill_reuse_with(state, prompt, progress) .map(|r| r.map(|r| r.reused)) .map_err(|e| e.to_string()) } fn logits(&self) -> &[f32] { &self.state().logits } fn advance(&mut self, token: u32) -> Result<(), String> { let state = &mut self.slots[self.active].state; let position = state.cached_tokens().len(); self.model .forward(state, token, position) .map(|_| ()) .map_err(|e| e.to_string()) } fn speculating(&self) -> bool { self.speculate } fn cached_len(&self) -> usize { self.state().cached_tokens().len() } fn advance_many(&mut self, tokens: &[u32]) -> Result>, String> { let state = &mut self.slots[self.active].state; let position = state.cached_tokens().len(); self.model .logits_after_each(state, tokens, position) .map_err(|e| e.to_string()) } fn truncate(&mut self, len: usize) { self.slots[self.active].state.truncate(len); } }