//! Request-level rules of the Original serve path that need no device: admission, the sequencing of one request over //! the owners, and the classes a request ends in. The device owners sit behind [`Lifecycle`], so the order (reset when //! the previous request left state behind, condition the prompt up to its last token, decode) and its failure classes //! run over any owners, a scripted fake included. //! //! Original reference (`generate.cpp` serve): a request with `n + max_new + 8 > max_context` is refused before any //! work; the prompt is read through token n-2 and token n-1 is the first verify input. With the conversation cache //! ([`Lifecycle::resume`]) a request starts reading where an earlier one left a reusable prefix; without it every //! request starts from the empty prompt. /// `<|endoftext|>`: the Original's `--eos-ids` default is {248044, 248046}; the GGUF's `tokenizer.ggml.eos_token_id` is /// only 248046 (`<|im_end|>`), so a request that stops on the metadata id alone runs on past an `<|endoftext|>` /// (quality gate). pub const ENDOFTEXT_TOKEN: i32 = 248_044; /// The stop set of a request on the Original serve path: generate.cpp's `eos_ids` ({248044, 248046}) plus the model's /// own EOS id. pub fn original_stop_tokens(eos: u32) -> Vec { let eos = eos as i32; if eos == ENDOFTEXT_TOKEN { vec![eos] } else { vec![eos, ENDOFTEXT_TOKEN] } } /// Cells a request keeps free beyond `n + max_new`: the last verify window may overshoot by up to this. pub const CONTEXT_SLACK: usize = 8; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Admission { EmptyPrompt, NoOutput, /// `n + max_new + 8 > max_context`, or a count that does not fit the index space. Context, BadToken, } /// Refusal before any owner is touched. pub fn admit(prompt: &[i32], eos: &[i32], max_new: usize, spec_min_p: f32, max_context: i64) -> Result<(), Admission> { if prompt.is_empty() { return Err(Admission::EmptyPrompt); } if max_new == 0 { return Err(Admission::NoOutput); } if prompt.iter().chain(eos).any(|&t| !(0..248_320).contains(&t)) { return Err(Admission::BadToken); } let needed = prompt.len().checked_add(max_new).and_then(|n| n.checked_add(CONTEXT_SLACK)).ok_or(Admission::Context)?; if i64::try_from(needed).map_or(true, |needed| needed > max_context) { return Err(Admission::Context); } if !spec_min_p.is_finite() || !(0.0..=1.0).contains(&spec_min_p) { return Err(Admission::BadToken); } Ok(()) } /// How a request ended when it did not complete; `E` is the owners' forward error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ServeError { /// Refused before any owner was touched. Refused(Admission), /// The caller's cancel flag ended the request (the owners were closed cleanly or will be reset). Cancelled, /// A forward/commit/draft failure; the next request starts from a reset. Failed(E), /// The owners could not be brought back to a usable state: the stack must not serve again. Broken(E), } /// What [`run_request`] needs from the device owners and the request type. pub trait Lifecycle { type Request; /// The owners' forward error. type Error: Copy; /// What ends a prompt or decode phase early: the caller's cancel, or a forward error. type Interrupted; type Outcome; /// Refusal before any owner is touched (see [`admit`]). fn admit(request: &Self::Request, max_context: i64) -> Result<(), Admission>; /// Prompt tokens of the request. fn prompt_len(request: &Self::Request) -> usize; /// The class a phase interruption ends the request in. fn classify(interrupted: Self::Interrupted) -> ServeError; /// The error of a resume point that would swallow the last prompt token. fn invalid_position() -> Self::Error; /// The error of a reset that reported success but left state behind. fn identity_mismatch() -> Self::Error; /// The session, draft ring and resident layers stand at the empty prompt (nothing to reset). fn is_fresh(&self) -> bool; /// Bring everything back to the empty prompt. A failure is `Broken`. fn reset(&mut self) -> Result<(), Self::Error>; /// Conversation cache (generate.cpp `--serve`): put the owners at the longest reusable prefix of the prompt (the /// live session, a checkpoint, or the empty prompt) and return how many prompt tokens are not read again. `None` /// when the cache is off or could not place the owners; the request then starts from the empty prompt through /// `is_fresh`/`reset`. fn resume(&mut self, request: &Self::Request) -> Option; /// Condition `prompt[resume..n-1]` into the session and the draft ring (they stand at `resume`). The interruption /// is a cancel only when the caller's flag fired. fn prefill bool>( &mut self, request: &Self::Request, resume: usize, cancel: &mut C, ) -> Result<(), Self::Interrupted>; /// Run the verified-window decode of the request; `emit` receives each committed round. fn decode Result<(), Self::Error>, C: FnMut() -> bool>( &mut self, request: &Self::Request, emit: &mut E, cancel: &mut C, ) -> Result; /// The request that `resume` placed is over (`Ok`, or how it ended); the conversation bookkeeping for the next one. fn finish(&mut self, ended: Result<(), ServeError>); } /// Place the request: how many prompt tokens are not read again. A cache that could not place the owners starts /// from the empty prompt (reset if the session is not fresh); a position past the prompt breaks the request. fn place_resume(owners: &mut L, request: &L::Request) -> Result> { match owners.resume(request) { Some(resume) if resume >= L::prompt_len(request) => { // the last prompt token always starts the first verify window owners.finish(Err(ServeError::Broken(L::invalid_position()))); Err(ServeError::Broken(L::invalid_position())) } Some(resume) => Ok(resume), None => { if !owners.is_fresh() { owners.reset().map_err(ServeError::Broken)?; if !owners.is_fresh() { return Err(ServeError::Broken(L::identity_mismatch())); } } Ok(0) } } } /// One request over the owners. pub fn run_request Result<(), L::Error>, C: FnMut() -> bool>( owners: &mut L, request: &L::Request, max_context: i64, emit: &mut E, cancel: &mut C, ) -> Result> { L::admit(request, max_context).map_err(ServeError::Refused)?; if cancel() { return Err(ServeError::Cancelled); } let resume = place_resume(owners, request)?; let served = owners .prefill(request, resume, cancel) .and_then(|()| owners.decode(request, emit, cancel)) .map_err(L::classify); owners.finish(served.as_ref().map(|_| ()).map_err(|e| *e)); served }