Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-serve-http/src/engine.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-serve-http / src / engine.rs` 480 lines ยท 18134 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! The engine seam: one blocking `generate` call per request, tokens in, tokens out. 17 //! 18 //! The HTTP layer never sees weights, sessions or logits. It renders the chat prompt 19 //! to token ids, takes the one generation lock, and calls [`Engine::generate`] on a 20 //! blocking thread. The engine prefills, decodes, samples, and hands each new token 21 //! to `on_token`; returning `false` from `on_token` cancels the generation (client 22 //! gone, or a stop string matched on the decoded text). 23 //! 24 //! Two engines ship here: [`StubEngine`] (tests, smoke without weights) and the CPU 25 //! reference forward in `cpu_engine.rs`. The Omega engine (own GPU kernels, no CUDA) 26 //! implements this same trait; the contract is written out in 27 //! `~/handoffs/own30b-engine-interface.md`. 28 29 use std::fmt; 30 use std::time::{Duration, Instant}; 31 32 use crate::sampling::SamplingRecord; 33 34 /// Sampling and stopping parameters for one generation. All fields are already 35 /// validated and defaulted by the HTTP layer. 36 #[derive(Debug, Clone, PartialEq)] 37 pub struct GenerateParams { 38 /// Hard cap on emitted tokens (stop tokens are not emitted and do not count). 39 pub max_new_tokens: usize, 40 /// `<= 0.001` means greedy (argmax). 41 pub temperature: f32, 42 /// Nucleus mass in `(0, 1]`; `1.0` disables nucleus filtering. 43 pub top_p: f32, 44 /// Keep only the `top_k` highest logits before sampling; `0` disables. 45 pub top_k: usize, 46 /// Request seed; engines derive a per-step seed from it so replays match. 47 pub seed: u64, 48 /// Token ids that end the generation (the model's eos set plus any extras). 49 pub stop_token_ids: Vec, 50 } 51 52 /// Why a generation ended. 53 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 54 pub enum FinishReason { 55 /// A stop token id was produced (not emitted). 56 Stop, 57 /// `max_new_tokens` reached, or the context window is full. 58 Length, 59 /// `on_token` returned `false`. 60 Cancelled, 61 } 62 63 /// What the engine reports when `generate` returns. 64 #[derive(Debug, Clone, PartialEq)] 65 pub struct GenerateOutcome { 66 /// Tokens handed to `on_token`. 67 pub emitted_tokens: usize, 68 pub finish: FinishReason, 69 pub prefill_ms: u64, 70 pub decode_ms: u64, 71 /// How the tokens were sampled, observed at each draw (OWN-8B stage S). `None` for an 72 /// engine that does not sample (the stub replays a fixed list). 73 pub sampling: Option, 74 } 75 76 #[derive(Debug, Clone, PartialEq, Eq)] 77 pub enum EngineError { 78 /// The prompt does not fit the engine's context window. 79 PromptTooLong { len: usize, max: usize }, 80 /// Anything else; the message is returned to the client verbatim. 81 Failed(String), 82 /// The shared chip is held by another job; the server answers 503 and the client retries. 83 Busy(String), 84 /// Memory admission refused the prompt (it would need more host memory than is free); the 85 /// server answers 413 `prompt_exceeds_memory_budget`, the same as a refusal in `prepare`. 86 MemoryExceeded(String), 87 } 88 89 impl fmt::Display for EngineError { 90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 91 match self { 92 Self::PromptTooLong { len, max } => { 93 write!( 94 f, 95 "prompt of {len} tokens exceeds the context window of {max}" 96 ) 97 } 98 Self::MemoryExceeded(m) => write!(f, "{m}"), 99 Self::Failed(m) => write!(f, "engine failed: {m}"), 100 Self::Busy(m) => write!(f, "GPU busy with another job: {m}"), 101 } 102 } 103 } 104 105 impl std::error::Error for EngineError {} 106 107 /// A text generation engine. `generate` blocks the calling thread for the whole 108 /// generation; the server runs it on a blocking thread while holding the one 109 /// generation lock, so an engine never sees two generations at once. 110 pub trait Engine: Send + Sync { 111 /// Short label of the engine kind, e.g. `stub`, `cpu-reference`, `omega`. 112 fn kind(&self) -> &str; 113 /// Largest prompt + generation length (in tokens) the engine accepts. 114 fn max_context_tokens(&self) -> usize; 115 /// Prefill `prompt`, then decode until a stop id, `max_new_tokens`, the context 116 /// limit, or `on_token` returning `false`. Stop ids are never passed to `on_token`. 117 fn generate( 118 &self, 119 prompt: &[u32], 120 params: &GenerateParams, 121 on_token: &mut dyn FnMut(u32) -> bool, 122 ) -> Result; 123 /// Memory admission, asked before the generation lock: `Err(why)` when `prompt` would need 124 /// more host memory than the machine has free, so the server can answer with a clear 4xx 125 /// instead of letting the kernel OOM-kill the process. The default admits everything. 126 fn admit(&self, _prompt: &[u32]) -> Result<(), String> { 127 Ok(()) 128 } 129 /// Persistent KV status and counters for `/health` (sc#505). `None` (the default, and the 130 /// omega door with `AIEN_KV_STORE_DIR` unset) leaves `/health` exactly as it was. 131 fn persistence_status(&self) -> Option { 132 None 133 } 134 /// How many generations the engine runs at once (the server hands out that many 135 /// permits). 1 for every engine that takes one `generate` at a time; a batching engine 136 /// says how many conversations it stacks on one weight read. 137 fn concurrency(&self) -> usize { 138 1 139 } 140 /// The merge train's per-request switches this engine honors (`TestSwitches` field names). 141 /// Empty for every engine without them; the server refuses a request whose `aien_test` 142 /// names a switch outside this list, so a switch is never ignored in silence. 143 fn test_switches_honored(&self) -> &'static [&'static str] { 144 &[] 145 } 146 /// `generate` with the merge train's switches applied to this one request. The default 147 /// refuses any switch (no engine honors one unless it says so) and is plain `generate` 148 /// for an empty set. 149 fn generate_with_test( 150 &self, 151 prompt: &[u32], 152 params: &GenerateParams, 153 test: &TestSwitches, 154 on_token: &mut dyn FnMut(u32) -> bool, 155 ) -> Result { 156 if !test.is_empty() { 157 return Err(EngineError::Failed(format!( 158 "aien_test switches {:?} are not honored by the {} engine", 159 test.names(), 160 self.kind() 161 ))); 162 } 163 self.generate(prompt, params, on_token) 164 } 165 /// Runs several generations that belong together (the eight readers of one long input, sc 166 /// L371) and returns one outcome per job, in order. `on_token(i, tok)` gets job `i`'s tokens; 167 /// `false` cancels that job only. The default runs them in turn; a batching engine seats them 168 /// all in the same beat so they share every weight read. The caller holds `jobs.len()` 169 /// permits (or all of them, when fewer). 170 fn generate_group( 171 &self, 172 jobs: &[GroupJob], 173 on_token: &mut dyn FnMut(usize, u32) -> bool, 174 ) -> Vec> { 175 let stopped = |j: &GroupJob| { 176 j.cancel 177 .as_ref() 178 .is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst)) 179 }; 180 jobs.iter() 181 .enumerate() 182 .map(|(i, j)| { 183 if stopped(j) { 184 return Ok(GenerateOutcome { 185 emitted_tokens: 0, 186 finish: FinishReason::Cancelled, 187 prefill_ms: 0, 188 decode_ms: 0, 189 sampling: None, 190 }); 191 } 192 self.generate_with_test(&j.prompt, &j.params, &j.test, &mut |t| { 193 on_token(i, t) && !stopped(j) 194 }) 195 }) 196 .collect() 197 } 198 } 199 200 /// The merge train's per-request switches (L384, Drake 2026-10-21: "batch these tests 201 /// together"): one loaded test server runs every lever's on/off and mutant cases, each request 202 /// saying which path it takes. `None` = the server's default. Only a build with the cargo 203 /// feature `aien-test-switches` applies them; every other build refuses a request that carries 204 /// `aien_test` (a live server never serves a mutant by accident, and never ignores a switch). 205 #[derive(Debug, Clone, Default, PartialEq, Eq)] 206 pub struct TestSwitches { 207 /// Rows ride L312's strokes (`false`: this row's own one-row graph, in turn). 208 pub stroke: Option, 209 /// L314's exact two-pass head for this row's greedy steps (`false`: the plain head). 210 pub exact_head: Option, 211 /// Negative control: the graph mutant (`AIEN_Q36_TEST_MUTANT` numbers) for this row only. 212 pub mutant: Option, 213 /// Negative control: at this request's `k`th decode step (from 1) it trades rows with 214 /// another live conversation; both must go red. 215 pub row_swap: Option, 216 /// L369 chunked prompt reading: tokens per chunk for this prompt (`0` = token by token). 217 pub prefill_chunk: Option, 218 /// L375 shared prompt cache: may this request read from or write to the pool. 219 pub prefix_pool: Option, 220 /// L313 bf16 DeltaNet state: load-only on the chip (the train starts a second server 221 /// for it); listed so a case can name it and the server can say so. 222 pub state_bf16: Option, 223 } 224 225 impl TestSwitches { 226 /// Every switch name, in the request's spelling. 227 pub const NAMES: [&'static str; 7] = [ 228 "stroke", 229 "exact_head", 230 "mutant", 231 "row_swap", 232 "prefill_chunk", 233 "prefix_pool", 234 "state_bf16", 235 ]; 236 237 /// Parses the request's `aien_test` object; an unknown key or a wrong type is an error (a 238 /// misspelt switch must never pass as "default"). 239 pub fn from_json(v: &serde_json::Value) -> Result { 240 let Some(map) = v.as_object() else { 241 return Err("aien_test must be an object".into()); 242 }; 243 let mut t = Self::default(); 244 for (k, v) in map { 245 if v.is_null() { 246 continue; 247 } 248 let bool_ = || { 249 v.as_bool() 250 .ok_or_else(|| format!("aien_test.{k} must be a boolean")) 251 }; 252 let uint = || { 253 v.as_u64() 254 .ok_or_else(|| format!("aien_test.{k} must be a whole number >= 0")) 255 }; 256 match k.as_str() { 257 "stroke" => t.stroke = Some(bool_()?), 258 "exact_head" => t.exact_head = Some(bool_()?), 259 "mutant" => { 260 let m = v 261 .as_i64() 262 .filter(|m| (0..=64).contains(m)) 263 .ok_or_else(|| format!("aien_test.{k} must be a whole number 0..=64"))?; 264 t.mutant = Some(m as i32); 265 } 266 "row_swap" => t.row_swap = Some(uint()?), 267 "prefill_chunk" => t.prefill_chunk = Some(uint()? as usize), 268 "prefix_pool" => t.prefix_pool = Some(bool_()?), 269 "state_bf16" => t.state_bf16 = Some(bool_()?), 270 other => return Err(format!("aien_test.{other}: no such switch")), 271 } 272 } 273 Ok(t) 274 } 275 276 /// The switches this request sets, by name. 277 pub fn names(&self) -> Vec<&'static str> { 278 let mut n = Vec::new(); 279 if self.stroke.is_some() { 280 n.push("stroke"); 281 } 282 if self.exact_head.is_some() { 283 n.push("exact_head"); 284 } 285 if self.mutant.is_some() { 286 n.push("mutant"); 287 } 288 if self.row_swap.is_some() { 289 n.push("row_swap"); 290 } 291 if self.prefill_chunk.is_some() { 292 n.push("prefill_chunk"); 293 } 294 if self.prefix_pool.is_some() { 295 n.push("prefix_pool"); 296 } 297 if self.state_bf16.is_some() { 298 n.push("state_bf16"); 299 } 300 n 301 } 302 303 pub fn is_empty(&self) -> bool { 304 *self == Self::default() 305 } 306 } 307 308 /// One generation of a [`Engine::generate_group`]. 309 #[derive(Debug, Clone)] 310 pub struct GroupJob { 311 pub prompt: Vec, 312 pub params: GenerateParams, 313 /// Set by the caller to stop this job even before it emits a token (a reader still taking in 314 /// its part when the client leaves). `None`: only `on_token` returning `false` stops it. 315 pub cancel: Option>, 316 /// The merge train's switches for this job (empty on the served path). 317 pub test: TestSwitches, 318 } 319 320 /// Test engine: ignores the prompt and replays a fixed token list, optionally 321 /// sleeping between tokens so tests can observe a busy server. 322 #[derive(Debug, Clone)] 323 pub struct StubEngine { 324 reply: Vec, 325 per_token_delay: Duration, 326 max_context: usize, 327 /// `Some(why)`: [`Engine::admit`] refuses every prompt (tests the memory-refusal answer). 328 admit_refusal: Option, 329 /// `Some(why)`: `generate` refuses with [`EngineError::MemoryExceeded`] after `admit` passed 330 /// (memory fell between the server's check and the engine's own, as in the omega door). 331 generate_refusal: Option, 332 } 333 334 impl StubEngine { 335 pub fn new(reply: Vec) -> Self { 336 Self { 337 reply, 338 per_token_delay: Duration::ZERO, 339 max_context: 4096, 340 admit_refusal: None, 341 generate_refusal: None, 342 } 343 } 344 345 pub fn with_delay(mut self, per_token_delay: Duration) -> Self { 346 self.per_token_delay = per_token_delay; 347 self 348 } 349 350 pub fn with_max_context(mut self, max_context: usize) -> Self { 351 self.max_context = max_context; 352 self 353 } 354 355 pub fn with_admit_refusal(mut self, why: &str) -> Self { 356 self.admit_refusal = Some(why.to_string()); 357 self 358 } 359 360 pub fn with_generate_refusal(mut self, why: &str) -> Self { 361 self.generate_refusal = Some(why.to_string()); 362 self 363 } 364 } 365 366 impl Engine for StubEngine { 367 fn kind(&self) -> &str { 368 "stub" 369 } 370 371 fn admit(&self, _prompt: &[u32]) -> Result<(), String> { 372 self.admit_refusal.clone().map_or(Ok(()), Err) 373 } 374 375 fn max_context_tokens(&self) -> usize { 376 self.max_context 377 } 378 379 fn generate( 380 &self, 381 prompt: &[u32], 382 params: &GenerateParams, 383 on_token: &mut dyn FnMut(u32) -> bool, 384 ) -> Result { 385 if prompt.is_empty() { 386 return Err(EngineError::Failed("empty prompt".into())); 387 } 388 if let Some(why) = &self.generate_refusal { 389 return Err(EngineError::MemoryExceeded(why.clone())); 390 } 391 if prompt.len() >= self.max_context { 392 return Err(EngineError::PromptTooLong { 393 len: prompt.len(), 394 max: self.max_context, 395 }); 396 } 397 let t0 = Instant::now(); 398 let mut emitted = 0usize; 399 let mut finish = FinishReason::Stop; 400 for &tok in &self.reply { 401 if emitted >= params.max_new_tokens || prompt.len() + emitted >= self.max_context { 402 finish = FinishReason::Length; 403 break; 404 } 405 if params.stop_token_ids.contains(&tok) { 406 finish = FinishReason::Stop; 407 break; 408 } 409 if !self.per_token_delay.is_zero() { 410 std::thread::sleep(self.per_token_delay); 411 } 412 emitted += 1; 413 if !on_token(tok) { 414 finish = FinishReason::Cancelled; 415 break; 416 } 417 } 418 Ok(GenerateOutcome { 419 emitted_tokens: emitted, 420 finish, 421 prefill_ms: 0, 422 decode_ms: t0.elapsed().as_millis() as u64, 423 sampling: None, 424 }) 425 } 426 } 427 428 #[cfg(test)] 429 mod tests { 430 use super::*; 431 432 fn params(max_new: usize) -> GenerateParams { 433 GenerateParams { 434 max_new_tokens: max_new, 435 temperature: 0.0, 436 top_p: 1.0, 437 top_k: 0, 438 seed: 1, 439 stop_token_ids: vec![99], 440 } 441 } 442 443 #[test] 444 fn stub_replays_until_stop_id() { 445 let e = StubEngine::new(vec![1, 2, 99, 3]); 446 let mut got = Vec::new(); 447 let out = e.generate(&[7], ¶ms(10), &mut |t| { 448 got.push(t); 449 true 450 }); 451 let out = out.expect("stub generates"); 452 assert_eq!(got, vec![1, 2]); 453 assert_eq!(out.finish, FinishReason::Stop); 454 assert_eq!(out.emitted_tokens, 2); 455 } 456 457 #[test] 458 fn stub_honours_max_new_tokens_and_cancel() { 459 let e = StubEngine::new(vec![1, 2, 3, 4]); 460 let out = e.generate(&[7], ¶ms(2), &mut |_| true).expect("ok"); 461 assert_eq!(out.finish, FinishReason::Length); 462 assert_eq!(out.emitted_tokens, 2); 463 let out = e.generate(&[7], ¶ms(9), &mut |_| false).expect("ok"); 464 assert_eq!(out.finish, FinishReason::Cancelled); 465 assert_eq!(out.emitted_tokens, 1); 466 } 467 468 #[test] 469 fn stub_refuses_empty_or_oversized_prompt() { 470 let e = StubEngine::new(vec![1]).with_max_context(4); 471 assert!(matches!( 472 e.generate(&[], ¶ms(1), &mut |_| true), 473 Err(EngineError::Failed(_)) 474 )); 475 assert_eq!( 476 e.generate(&[1, 2, 3, 4], ¶ms(1), &mut |_| true), 477 Err(EngineError::PromptTooLong { len: 4, max: 4 }) 478 ); 479 } 480 }