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/omega_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 / omega_engine.rs` 1285 lines ยท 52145 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 Omega engine behind the door (OWN-30B cut 8): Qwen3-30B-A3B on AIEN's own GPU 17 //! kernels, FP8 weights resident between requests, prefix KV reuse across turns, and the 18 //! shared-chip lock taken only around each generation. 19 //! 20 //! Chip etiquette: `/tmp/aien-gb10.lock` is the hive's GPU lock. The server never holds it 21 //! while idle; `generate` takes it (waiting up to [`LOCK_WAIT`]) and releases it when the 22 //! reply is done. If another job holds it past the wait the request fails with 23 //! [`EngineError::Busy`], which the server turns into HTTP 503. 24 25 use std::fs::{File, OpenOptions}; 26 use std::os::fd::AsRawFd; 27 use std::path::{Path, PathBuf}; 28 #[cfg(test)] 29 use std::sync::atomic::AtomicBool; 30 use std::sync::atomic::{AtomicUsize, Ordering}; 31 use std::time::{Duration, Instant}; 32 33 use aien_inference_abi::qwen3_moe_omega::{self as omega, LoadReport, OmegaEngine, WeightFormat}; 34 use aien_inference_abi::qwen3_moe_omega::{ 35 PrefillGrowth, WholePromptFootprint, SCRATCH_BYTES_PER_TOKEN, 36 }; 37 38 use crate::engine::{Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams}; 39 use crate::kv_persist::PersistState; 40 use crate::sampling::SamplingObserver; 41 42 pub const GPU_LOCK_PATH: &str = "/tmp/aien-gb10.lock"; 43 44 /// How long `generate` waits for the chip lock before answering busy. 45 pub const LOCK_WAIT: Duration = Duration::from_secs(30); 46 /// Host memory the load needs free (the model is 30.5 GB resident plus the KV pool and 47 /// loader transients; the rule leaves room for another 30 GB job). 48 pub const LOAD_MIN_FREE_GB: f64 = 45.0; 49 /// Host memory a prefill must leave free (the box also runs the other model, builds and tests). 50 pub const ADMIT_RESERVE_BYTES: u64 = 6 << 30; 51 /// Environment override of tokens per whole-prompt pass. Unset keeps the engine default 52 /// ([`aien_inference_abi::qwen3_moe_omega::DEFAULT_CHUNK`], one pass). `8192` opts into 53 /// chunked prefill. `0` is one pass. 54 pub const WP_CHUNK_ENV: &str = "AIEN_SERVE_WP_CHUNK"; 55 56 /// `MemAvailable` from `/proc/meminfo` text, bytes. 57 pub fn parse_mem_available(meminfo: &str) -> Option { 58 let line = meminfo.lines().find(|l| l.starts_with("MemAvailable:"))?; 59 let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?; 60 Some(kb * 1024) 61 } 62 63 /// Admission rule: the prefill's growth plus [`ADMIT_RESERVE_BYTES`] must fit `available`. 64 /// `Err` names the numbers and the longest prompt that would pass right now. `None` (meminfo 65 /// unreadable) admits, and so does a prefill that adds nothing (a warm chunked path, or the 66 /// whole-prompt path off): refusing it would not keep a byte free. 67 pub fn admit_growth( 68 growth: PrefillGrowth, 69 available: Option, 70 prompt_tokens: usize, 71 ) -> Result<(), String> { 72 let Some(avail) = available else { 73 return Ok(()); 74 }; 75 if growth.total() == 0 { 76 return Ok(()); 77 } 78 let gb = |b: u64| b as f64 / 1e9; 79 if avail >= growth.total().saturating_add(ADMIT_RESERVE_BYTES) { 80 return Ok(()); 81 } 82 let room = avail 83 .saturating_sub(ADMIT_RESERVE_BYTES) 84 .saturating_sub(growth.mirror_bytes); 85 let fits = room / SCRATCH_BYTES_PER_TOKEN; 86 // `fits == 0` is not a length the client can send. Saying "at most about 0 tokens" left a 87 // cold server with no request that could ever warm the KV mirror. 88 let advice = if fits == 0 { 89 "retry when memory is free (nothing shorter fits beside the KV mirror and the reserve)" 90 .to_string() 91 } else { 92 format!("retry when memory is free or send at most about {fits} tokens now") 93 }; 94 Err(format!( 95 "prompt of {prompt_tokens} tokens needs {:.1} GB more host memory ({:.1} GB KV mirror + {:.1} GB prompt scratch) but only {:.1} GB is available and {:.0} GB must stay free; {advice}", 96 gb(growth.total()), 97 gb(growth.mirror_bytes), 98 gb(growth.scratch_bytes), 99 gb(avail), 100 gb(ADMIT_RESERVE_BYTES), 101 )) 102 } 103 104 /// What the door runs after admission. 105 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 106 pub enum PrefillAdmit { 107 /// The whole-prompt driver, including its KV mirror on the first pass. 108 WholePrompt, 109 /// Whole-prompt does not fit and the mirror is not live. The classic prefill loop does 110 /// not allocate the mirror, at every free-memory reading: a tighter box must not be 111 /// served while a looser one is refused. 112 Classic, 113 } 114 115 /// Tokens the engine prefills: `prompt[reused..]`. `reused` is the reusable prefix 116 /// (common history, at most `prompt_len - 1`, because the last prompt token is always stepped). 117 pub fn priced_tokens(prompt_len: usize, reused: usize) -> usize { 118 let kept = reused.min(prompt_len.saturating_sub(1)); 119 prompt_len.saturating_sub(kept) 120 } 121 122 /// Admission for one prompt. `prompt_tokens` is the uncached suffix ([`priced_tokens`]), not 123 /// the whole prompt. More free memory never turns a serve into a refusal: when whole-prompt 124 /// fits it is used; when it does not and the mirror is not live, the classic path serves at 125 /// every reading (11 GB and 20 GB alike). A live mirror prices scratch only, so a refusal 126 /// there stays a refusal at every lower reading. 127 pub fn admit_request( 128 fp: &WholePromptFootprint, 129 available: Option, 130 prompt_tokens: usize, 131 ) -> Result { 132 if !fp.on { 133 return Ok(PrefillAdmit::WholePrompt); 134 } 135 let growth = fp.growth(prompt_tokens); 136 if admit_growth(growth, available, prompt_tokens).is_ok() { 137 return Ok(PrefillAdmit::WholePrompt); 138 } 139 if !fp.mirror_live && growth.mirror_bytes > 0 { 140 return Ok(PrefillAdmit::Classic); 141 } 142 admit_growth(growth, available, prompt_tokens).map(|()| PrefillAdmit::WholePrompt) 143 } 144 145 /// Prefill path of the door (OWN-30B release candidate, W-RC 2026-10-14). Both switches are ON 146 /// by default: the whole prompt goes through omega's prefill GEMMs and attention in one pass 147 /// (`set_whole_prompt`), with the router logits and MoE combine on the chip 148 /// (`set_whole_prompt_device_host`). Chip gate (sc own30b/whole-prompt `7cc2b66`): TTFT 512 tokens 149 /// 7.6 s -> 0.31 s, 2048 tokens 31.4 s -> 0.84 s; tokens differ from the chunked path only by FP8 150 /// activation rounding. Off: `--whole-prompt off` / `AIEN_SERVE_WHOLE_PROMPT=0` (the chunked 151 /// prefill of cut 10), `--prefill-device-host off` / `AIEN_SERVE_WP_DEVICE_HOST=0` (host routing 152 /// and combine). The cached 30 GB weight copy and speculative decoding stay off. 153 /// 154 /// Defaults differ by path (sc#522); this is documented, not aligned, because changing a chip 155 /// tool's default would change what its past evidence means: 156 /// - this door: both ON ([`Default`]; `--whole-prompt off` / `--prefill-device-host off`); 157 /// - the engine itself (`Qwen3MoeOmegaEngine`): both OFF until `set_whole_prompt(true)` and 158 /// `set_whole_prompt_device_host(true)`; its other callers (`own30b_ttft`, `own30b_wp_gate`) 159 /// set the switch explicitly per leg; 160 /// - `own30b_check`: both OFF unless the bare flags `--whole-prompt` and 161 /// `--prefill-device-host` are passed. 162 /// 163 /// A door run and a check run therefore use different prefill paths unless the check is given 164 /// both flags (or the door both `off` switches); their tokens can differ by FP8 activation 165 /// rounding. Compare like with like. 166 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 167 pub struct PrefillMode { 168 pub whole_prompt: bool, 169 pub device_host: bool, 170 } 171 172 impl Default for PrefillMode { 173 fn default() -> Self { 174 Self { 175 whole_prompt: true, 176 device_host: true, 177 } 178 } 179 } 180 181 /// Environment switch for [`PrefillMode::whole_prompt`]. 182 pub const WHOLE_PROMPT_ENV: &str = "AIEN_SERVE_WHOLE_PROMPT"; 183 /// Environment switch for [`PrefillMode::device_host`]. 184 pub const WP_DEVICE_HOST_ENV: &str = "AIEN_SERVE_WP_DEVICE_HOST"; 185 186 /// `on|off|1|0|true|false` (anything else is refused, so a typo never silently flips a path). 187 pub fn parse_switch(name: &str, v: &str) -> Result { 188 match v.trim().to_ascii_lowercase().as_str() { 189 "on" | "1" | "true" | "yes" => Ok(true), 190 "off" | "0" | "false" | "no" => Ok(false), 191 other => Err(format!("{name} must be on or off, got {other:?}")), 192 } 193 } 194 195 impl PrefillMode { 196 /// Defaults overridden by the environment (`None` = unset). 197 pub fn from_env(whole_prompt: Option<&str>, device_host: Option<&str>) -> Result { 198 let mut m = Self::default(); 199 if let Some(v) = whole_prompt { 200 m.whole_prompt = parse_switch(WHOLE_PROMPT_ENV, v)?; 201 } 202 if let Some(v) = device_host { 203 m.device_host = parse_switch(WP_DEVICE_HOST_ENV, v)?; 204 } 205 Ok(m) 206 } 207 208 /// What the engine runs: the device router/combine only exists inside the whole-prompt path. 209 pub fn effective(self) -> Self { 210 Self { 211 whole_prompt: self.whole_prompt, 212 device_host: self.whole_prompt && self.device_host, 213 } 214 } 215 } 216 217 /// An exclusive hold of the hive's GPU lock (released on drop), or nothing at all when an 218 /// ancestor verifiably holds it for this process's life ([`crate::chip_reservation`]). 219 pub struct GpuLock { 220 #[allow(dead_code)] 221 file: Option, 222 /// Runs while the flock is still held, before the file drops. Tests sample 223 /// suspension here: the next request cannot take the lock until this returns. 224 #[cfg(test)] 225 on_release: Option>, 226 } 227 228 impl GpuLock { 229 fn new(file: Option) -> Self { 230 Self { 231 file, 232 #[cfg(test)] 233 on_release: None, 234 } 235 } 236 237 #[cfg(test)] 238 fn on_release(&mut self, hook: impl FnOnce() + Send + 'static) { 239 self.on_release = Some(Box::new(hook)); 240 } 241 } 242 243 impl Drop for GpuLock { 244 fn drop(&mut self) { 245 #[cfg(test)] 246 if let Some(hook) = self.on_release.take() { 247 hook(); 248 } 249 } 250 } 251 252 impl GpuLock { 253 /// Takes the hive's lock ([`GPU_LOCK_PATH`]), polling until `wait` has passed. 254 /// `Err` = still held by someone else. 255 pub fn acquire(wait: Duration) -> Result { 256 Self::acquire_at(Path::new(GPU_LOCK_PATH), wait) 257 } 258 259 /// Under a verified inherited reservation there is nothing to take: `Some(lock)`. 260 fn inherited() -> Option { 261 crate::chip_reservation::inherited().then_some(Self::new(None)) 262 } 263 264 /// [`Self::acquire`] on the lock file at `path` (tests pass a private file). 265 pub fn acquire_at(path: &Path, wait: Duration) -> Result { 266 if let Some(l) = Self::inherited() { 267 return Ok(l); 268 } 269 let file = OpenOptions::new() 270 .read(true) 271 .write(true) 272 .create(true) 273 .truncate(false) 274 .open(path) 275 .map_err(|e| format!("{}: {e}", path.display()))?; 276 let t0 = Instant::now(); 277 loop { 278 // SAFETY: flock on a valid open descriptor; non-blocking so the wait is bounded. 279 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; 280 if rc == 0 { 281 return Ok(Self::new(Some(file))); 282 } 283 let err = std::io::Error::last_os_error(); 284 if err.raw_os_error() != Some(libc::EWOULDBLOCK) { 285 return Err(format!("flock {}: {err}", path.display())); 286 } 287 if t0.elapsed() >= wait { 288 return Err(format!( 289 "GPU lock held by another job for {} s", 290 wait.as_secs() 291 )); 292 } 293 std::thread::sleep(Duration::from_millis(50)); 294 } 295 } 296 } 297 298 impl GpuLock { 299 /// Takes the lock at `path` by waiting in the kernel's queue (a blocking `flock` on a helper 300 /// thread), so jobs that wait with `flock(1)` cannot starve it the way polling can. After 301 /// `wait` without the lock: `Err`, and the helper drops the lock the moment it gets it. 302 pub fn acquire_queued_at(path: &Path, wait: Duration) -> Result { 303 use std::sync::atomic::AtomicBool; 304 use std::sync::{mpsc, Arc}; 305 if let Some(l) = Self::inherited() { 306 return Ok(l); 307 } 308 let file = OpenOptions::new() 309 .read(true) 310 .write(true) 311 .create(true) 312 .truncate(false) 313 .open(path) 314 .map_err(|e| format!("{}: {e}", path.display()))?; 315 // SAFETY: flock on a valid open descriptor; non-blocking fast path. 316 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { 317 return Ok(Self::new(Some(file))); 318 } 319 let (tx, rx) = mpsc::channel(); 320 let gave_up = Arc::new(AtomicBool::new(false)); 321 let gave_up_t = Arc::clone(&gave_up); 322 let name = path.display().to_string(); 323 std::thread::spawn(move || { 324 // SAFETY: as above; blocks in the kernel's wait queue until the lock is ours. 325 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }; 326 let r = if rc == 0 { 327 Ok(file) 328 } else { 329 Err(format!("flock {name}: {}", std::io::Error::last_os_error())) 330 }; 331 if gave_up_t.load(Ordering::SeqCst) { 332 return; // dropping `r` closes the file and releases the lock 333 } 334 if let Err(mpsc::SendError(Ok(f))) = tx.send(r) { 335 drop(f); 336 } 337 }); 338 match rx.recv_timeout(wait) { 339 Ok(r) => r.map(|f| Self::new(Some(f))), 340 Err(_) => { 341 gave_up.store(true, Ordering::SeqCst); 342 // The helper may have sent just before the flag: take and drop it. 343 if let Ok(Ok(f)) = rx.try_recv() { 344 drop(f); 345 } 346 Err(format!( 347 "GPU lock held by other jobs for {} s", 348 wait.as_secs() 349 )) 350 } 351 } 352 } 353 } 354 355 /// `MemAvailable` from /proc/meminfo in GB (0 when unreadable). 356 pub fn mem_available_gb() -> f64 { 357 std::fs::read_to_string("/proc/meminfo") 358 .ok() 359 .and_then(|t| { 360 t.lines() 361 .find(|l| l.starts_with("MemAvailable:")) 362 .and_then(|l| l.split_whitespace().nth(1)) 363 .and_then(|v| v.parse::().ok()) 364 }) 365 .map(|kb| kb / 1024.0 / 1024.0) 366 .unwrap_or(0.0) 367 } 368 369 pub struct OmegaDoor { 370 /// Declared first: a running store drains its parks before the engine goes. 371 persist: PersistState, 372 engine: OmegaEngine, 373 lock_wait: Duration, 374 lock_path: PathBuf, 375 /// Prompt tokens the last generation reused (RAM or restored prefix). 376 reused_last: AtomicUsize, 377 /// The whole-prompt path's resident state after the last generation, for [`Engine::admit`]. 378 footprint: std::sync::Mutex, 379 /// Test seam: bytes `admit` treats as `MemAvailable`. `None` reads `/proc/meminfo`. 380 #[cfg(test)] 381 available_probe: Option Option + Send + Sync>>, 382 /// Test seam: runs where the persistent-KV fetch returns, before the GPU lock. The race 383 /// test drops the probe's available bytes here, the way a fetched payload drops 384 /// `MemAvailable`. 385 #[cfg(test)] 386 fetch_probe: Option>, 387 /// Mirrors `whole_prompt_suspended` for the lock-drop hook. Set with the suspension, 388 /// cleared by [`ResumeWholePrompt`]. 389 #[cfg(test)] 390 suspend_visible: std::sync::Arc, 391 /// Called from [`GpuLock`]'s drop, while the flock is still held. 392 #[cfg(test)] 393 lock_release_hook: Option>, 394 } 395 396 impl OmegaDoor { 397 /// A door over an already built engine, taking the GPU lock at `lock_path` around each 398 /// generation (tests: a private lock file and the host test engine). Persistence off. 399 pub fn from_parts(engine: OmegaEngine, lock_path: PathBuf, lock_wait: Duration) -> Self { 400 let footprint = engine 401 .with_engine(|e| e.whole_prompt_footprint()) 402 .unwrap_or_default(); 403 Self { 404 persist: PersistState::Off, 405 engine, 406 lock_wait, 407 lock_path, 408 reused_last: AtomicUsize::new(0), 409 footprint: std::sync::Mutex::new(footprint), 410 #[cfg(test)] 411 available_probe: None, 412 #[cfg(test)] 413 fetch_probe: None, 414 #[cfg(test)] 415 suspend_visible: std::sync::Arc::new(AtomicBool::new(false)), 416 #[cfg(test)] 417 lock_release_hook: None, 418 } 419 } 420 421 /// Uncached suffix `generate_inner` prefills (`prompt[reused..]`), after any restore 422 /// already imported into the engine. 423 fn prefill_len(&self, prompt: &[u32]) -> usize { 424 let reused = self 425 .engine 426 .with_engine(|e| e.reusable_prefix(prompt)) 427 .unwrap_or(0); 428 priced_tokens(prompt.len(), reused) 429 } 430 431 fn current_available(&self) -> Option { 432 #[cfg(test)] 433 if let Some(p) = &self.available_probe { 434 return p(); 435 } 436 std::fs::read_to_string("/proc/meminfo") 437 .ok() 438 .and_then(|m| parse_mem_available(&m)) 439 } 440 441 fn decide(&self, prompt_tokens: usize) -> Result { 442 let fp = self.footprint.lock().map_err(|e| e.to_string())?; 443 admit_request(&fp, self.current_available(), prompt_tokens) 444 } 445 446 /// Copies the engine footprint after `generate_with` returns, including on error. 447 /// `whole_prompt_mirror_live` is set only after a pass returns, so a pass that allocates 448 /// the mirror and then errors still reads cold. The next request over-charges that mirror. 449 /// The over-charge is the safe direction: this copy does not mark a mirror the engine has 450 /// not recorded. 451 fn note_footprint(&self) { 452 if let Ok(fp) = self.engine.with_engine(|e| e.whole_prompt_footprint()) { 453 if let Ok(mut slot) = self.footprint.lock() { 454 *slot = fp; 455 } 456 } 457 } 458 459 /// Drops the suspension guard, then the GPU lock. The guard's drop clears 460 /// `suspend_whole_prompt` while the flock is still held. 461 fn release_lock(&self, resume: ResumeWholePrompt<'_>, lock: GpuLock) { 462 #[cfg(test)] 463 { 464 let mut lock = lock; 465 if let Some(hook) = self.lock_release_hook.clone() { 466 lock.on_release(move || hook()); 467 } 468 drop(resume); 469 drop(lock); 470 } 471 #[cfg(not(test))] 472 { 473 drop(resume); 474 let _ = self; 475 drop(lock); 476 } 477 } 478 479 /// Installs the persistence state (`kv_persist::open`), before the door is shared. 480 pub fn set_persistence(&mut self, state: PersistState) { 481 self.persist = state; 482 } 483 484 pub fn persistence(&self) -> &PersistState { 485 &self.persist 486 } 487 488 /// The engine's run settings that can change a K/V byte (persistent KV identity). 489 pub fn kv_switches(&self) -> omega::OmegaKvSwitches { 490 self.engine 491 .with_engine(|e| e.kv_switches()) 492 .expect("engine lock") 493 } 494 495 /// The loaded model config. 496 pub fn config(&self) -> omega::Qwen3MoeConfig { 497 self.engine 498 .with_engine(|e| e.config().clone()) 499 .expect("engine lock") 500 } 501 502 /// Tokens whose KV the engine holds (the next turn's reuse candidates). 503 pub fn history(&self) -> Vec { 504 self.engine 505 .with_engine(|e| e.history().to_vec()) 506 .unwrap_or_default() 507 } 508 509 /// Prompt tokens the last generation did not prefill (kept in RAM or restored). 510 pub fn reused_last(&self) -> usize { 511 self.reused_last.load(Ordering::Relaxed) 512 } 513 514 /// The K/V of positions `0..len` as the persistent KV payload, under the GPU lock (the chip 515 /// check compares the uninterrupted and the restored run byte for byte). 516 pub fn export_kv_for_check(&self, len: usize) -> Result, String> { 517 let _lock = GpuLock::acquire_at(&self.lock_path, self.lock_wait)?; 518 self.engine.with_engine(|e| e.export_kv(0, len))? 519 } 520 521 /// Imports `payload` as the K/V of `tokens` (positions `0..tokens.len()`), under the GPU lock, 522 /// exactly as a restore does (the chip check times it and round-trips it against 523 /// [`Self::export_kv_for_check`]). On error the engine is reset. 524 pub fn restore_kv_for_check(&self, tokens: &[u32], payload: &[u8]) -> Result<(), String> { 525 let _lock = GpuLock::acquire_at(&self.lock_path, self.lock_wait)?; 526 self.engine.with_engine(|e| e.restore_kv(tokens, payload))? 527 } 528 529 /// Forgets the KV the engine holds (the next prompt is prefilled, or restored from the store). 530 pub fn reset_kv(&self) { 531 let _ = self.engine.with_engine(|e| e.reset()); 532 } 533 /// Loads the checkpoint onto Omega (under the GPU lock, released before returning) with a 534 /// KV for `max_context` tokens. Refuses with less than [`LOAD_MIN_FREE_GB`] available. 535 pub fn load( 536 model_dir: &Path, 537 max_context: usize, 538 format: WeightFormat, 539 spin_us: Option, 540 prefill: PrefillMode, 541 ) -> Result { 542 let avail = mem_available_gb(); 543 if avail < LOAD_MIN_FREE_GB { 544 return Err(format!("{avail:.1} GB available, the load needs {LOAD_MIN_FREE_GB} GB free (another model may be loaded)")); 545 } 546 if !aien_omega_gpu::is_native() { 547 return Err("this binary carries the CPU stub of the Omega engine".into()); 548 } 549 if format.fp8_experts() && !omega::OmegaModelUploader::uses_fp8_api() { 550 return Err("this binary has no FP8 GEMV linked; use --weights bf16 or link the integration omega".into()); 551 } 552 if let Some(us) = spin_us { 553 aien_omega_gpu::set_spin_us(us).map_err(|e| e.to_string())?; 554 } 555 let _lock = GpuLock::acquire(LOCK_WAIT)?; 556 let t0 = Instant::now(); 557 let mut n = 0usize; 558 let engine = OmegaEngine::load_with(model_dir, max_context, format, &mut |what| { 559 n += 1; 560 if n.is_multiple_of(24) || what.starts_with("kv") || what == "lm_head" { 561 eprintln!( 562 "aien-serve-http: omega load [{:.0}s] {what}", 563 t0.elapsed().as_secs_f64() 564 ); 565 } 566 })?; 567 // The KV cache may hold fewer positions than asked (the fused cache caps at 568 // aien_omega_dattn::MAX_POS): refuse instead of serving a shorter context than requested. 569 let context = engine.max_context_tokens(); 570 if context < max_context { 571 return Err(format!( 572 "--max-context {max_context}: the engine's KV cache holds at most {context} positions (start with --max-context {context} or less)" 573 )); 574 } 575 // Prefill path (W-RC): switched on while the load still holds the chip lock. A refusal is 576 // fatal: the operator asked for the path (by default), so say how to turn it off. 577 let prefill = prefill.effective(); 578 let t_wp = Instant::now(); 579 engine.with_engine(|e| -> Result<(), String> { 580 e.set_whole_prompt(prefill.whole_prompt) 581 .map_err(|m| format!("{m} (start with --whole-prompt off to use the chunked prefill)"))?; 582 if let Ok(v) = std::env::var(WP_CHUNK_ENV) { 583 let n: usize = v.trim().parse().map_err(|_| format!("{WP_CHUNK_ENV} must be a token count (0 = one pass), got {v:?}"))?; 584 e.set_whole_prompt_chunk(n); 585 } 586 if prefill.whole_prompt { 587 e.set_whole_prompt_device_host(prefill.device_host) 588 .map_err(|m| format!("{m} (start with --prefill-device-host off to keep routing on the host)"))?; 589 } 590 Ok(()) 591 })??; 592 let (wp_on, wp_dev) = 593 engine.with_engine(|e| (e.whole_prompt_on(), e.whole_prompt_device_host_on()))?; 594 eprintln!( 595 "aien-serve-http: whole_prompt={} prefill_device_host={} (set in {:.2} s)", 596 if wp_on { "on" } else { "off" }, 597 if wp_dev { "on" } else { "off" }, 598 t_wp.elapsed().as_secs_f64() 599 ); 600 let r = &engine.load_report; 601 let (attn_path, prefill_chunk, router_path, lm_head_path, prefill_path) = engine 602 .with_engine(|e| { 603 ( 604 e.attention_path(), 605 e.prefill_chunk, 606 if e.device_routing { "device" } else { "host" }, 607 if matches!(e.weights().lm_head, omega::LmHead::Gemv(_)) { 608 "gemv" 609 } else { 610 "dense" 611 }, 612 if e.prefill_gemm { "gemm" } else { "gemv" }, 613 ) 614 })?; 615 eprintln!( 616 "aien-serve-http: omega engine ready in {:.1} s: context {context} tokens, {:?} weights, {:.2} GB resident, {:.2} GB host, peak rss {:.2} GB, window_api={} fp8_api={} dattn_api={} attention={attn_path} router={router_path} lm_head={lm_head_path} prefill={prefill_path} prefill_chunk={prefill_chunk} spin_us={:?}", 617 r.seconds, 618 r.format, 619 r.resident_bytes as f64 / 1e9, 620 r.host_bytes as f64 / 1e9, 621 r.peak_rss_bytes.unwrap_or(0) as f64 / 1e9, 622 r.window_api, 623 omega::OmegaModelUploader::uses_fp8_api(), 624 omega::OmegaModelUploader::uses_dattn_api(), 625 aien_omega_gpu::spin_us(), 626 ); 627 Ok(Self::from_parts( 628 engine, 629 PathBuf::from(GPU_LOCK_PATH), 630 LOCK_WAIT, 631 )) 632 } 633 634 pub fn load_report(&self) -> &LoadReport { 635 &self.engine.load_report 636 } 637 638 /// Tokens whose KV is resident from the last generation (prefix reuse candidates). 639 pub fn history_len(&self) -> usize { 640 self.engine.with_engine(|e| e.history().len()).unwrap_or(0) 641 } 642 } 643 644 /// Clears a one-request classic-prefill suspension. Drop it before the GPU lock: the next 645 /// request can take the lock only after that drop has run. 646 struct ResumeWholePrompt<'a> { 647 engine: &'a omega::OmegaEngine, 648 #[cfg(test)] 649 visible: Option>, 650 } 651 652 impl Drop for ResumeWholePrompt<'_> { 653 fn drop(&mut self) { 654 let _ = self.engine.with_engine(|e| e.suspend_whole_prompt(false)); 655 #[cfg(test)] 656 if let Some(v) = &self.visible { 657 v.store(false, Ordering::SeqCst); 658 } 659 } 660 } 661 662 impl Engine for OmegaDoor { 663 fn kind(&self) -> &str { 664 self.engine.kind() 665 } 666 667 fn max_context_tokens(&self) -> usize { 668 self.engine.max_context_tokens() 669 } 670 671 fn admit(&self, prompt: &[u32]) -> Result<(), String> { 672 // Early check, before the generation lock. Prices the uncached suffix already in 673 // RAM. `generate` restores persistent KV, then prices `prompt[reused..]` again. 674 self.decide(self.prefill_len(prompt)).map(|_| ()) 675 } 676 677 fn generate( 678 &self, 679 prompt: &[u32], 680 p: &GenerateParams, 681 on_token: &mut dyn FnMut(u32) -> bool, 682 ) -> Result { 683 let max = self.engine.max_context_tokens(); 684 if prompt.is_empty() { 685 return Err(EngineError::Failed("empty prompt".into())); 686 } 687 if prompt.len() >= max { 688 return Err(EngineError::PromptTooLong { 689 len: prompt.len(), 690 max, 691 }); 692 } 693 let q = omega::GenerateParams { 694 max_new_tokens: p.max_new_tokens, 695 temperature: p.temperature, 696 top_p: p.top_p, 697 top_k: p.top_k, 698 seed: p.seed, 699 stop_token_ids: p.stop_token_ids.clone(), 700 }; 701 // Persistent KV (sc#505), off unless AIEN_KV_STORE_DIR asked for it: look up and load 702 // the longest stored prefix that beats the RAM prefix, without the chip lock. 703 let persist = match &self.persist { 704 PersistState::On(pk) => Some(pk.as_ref()), 705 _ => None, 706 }; 707 let fetched = persist.filter(|pk| pk.restore_on()).and_then(|pk| { 708 let in_ram = self 709 .engine 710 .with_engine(|e| e.reusable_prefix(prompt)) 711 .unwrap_or(0); 712 pk.fetch(prompt, in_ram) 713 }); 714 #[cfg(test)] 715 if let Some(p) = &self.fetch_probe { 716 p(); 717 } 718 let t_lock = Instant::now(); 719 let lock = match GpuLock::acquire_at(&self.lock_path, self.lock_wait) { 720 Ok(l) => l, 721 Err(e) => { 722 // A prefix loaded but never imported is a restore miss, not lost from the counters. 723 if let (Some(pk), Some(_)) = (persist, fetched.as_ref()) { 724 pk.note_lock_busy(); 725 } 726 return Err(EngineError::Busy(e)); 727 } 728 }; 729 let lock_wait_ms = t_lock.elapsed().as_millis(); 730 // Restore before admission so the reusable prefix includes the imported tokens. 731 // `note_restored` waits until admission succeeds: a 413 must not count a restore. 732 let mut restored = false; 733 if let (Some(pk), Some(f)) = (persist, fetched.as_ref()) { 734 // All or nothing: on error the engine is reset and the prompt is prefilled. 735 match self 736 .engine 737 .with_engine(|e| e.restore_kv(&prompt[..f.tokens], &f.payload)) 738 { 739 Ok(Ok(())) => restored = true, 740 Ok(Err(m)) | Err(m) => { 741 pk.note_import_failed(); 742 eprintln!("aien-serve-http: persistent KV: restore of {} tokens refused ({m}); prefilling", f.tokens); 743 } 744 } 745 } 746 // The payload is still resident here, and the lock wait has already happened, so this 747 // reading sees both. The length is the uncached suffix, not the whole prompt. 748 let admission = match self.decide(self.prefill_len(prompt)) { 749 Ok(a) => a, 750 Err(m) => { 751 if restored { 752 let _ = self.engine.with_engine(|e| e.reset()); 753 } 754 return Err(EngineError::MemoryExceeded(m)); 755 } 756 }; 757 if restored { 758 if let (Some(pk), Some(f)) = (persist, fetched.as_ref()) { 759 pk.note_restored(f); 760 } 761 } 762 let classic = matches!(admission, PrefillAdmit::Classic); 763 #[cfg(test)] 764 self.suspend_visible.store(classic, Ordering::SeqCst); 765 self.engine 766 .with_engine(|e| e.suspend_whole_prompt(classic)) 767 .map_err(EngineError::Failed)?; 768 let resume = ResumeWholePrompt { 769 engine: &self.engine, 770 #[cfg(test)] 771 visible: Some(std::sync::Arc::clone(&self.suspend_visible)), 772 }; 773 drop(fetched); 774 // The server's own sampler, so CPU and Omega engines pick tokens the same way. 775 let mut observer = SamplingObserver::new(p); 776 let mut sampler = |logits: &[f32], step: usize| observer.sample(logits, step); 777 let generated = self 778 .engine 779 .generate_with(prompt, &q, &mut sampler, on_token); 780 // Copy the footprint the engine recorded. A pass that errors before it sets 781 // `whole_prompt_mirror_live` still reads cold (see `note_footprint`). 782 self.note_footprint(); 783 let o = generated.map_err(EngineError::Failed)?; 784 let sampling = observer.record(); 785 self.reused_last 786 .store(o.reused_prompt_tokens, Ordering::Relaxed); 787 // Park: export under the chip lock, write after it is released. A classic fallback did 788 // not run the configured whole-prompt path, so its KV is not stored under that identity. 789 let parked = if classic { 790 None 791 } else { 792 persist.map(|pk| { 793 self.engine 794 .with_engine(|e| pk.snapshot(e)) 795 .unwrap_or_default() 796 }) 797 }; 798 // Clear the suspension while the flock is still held, then drop the lock. 799 // The other order lets the next request set suspend(true) and then lose it 800 // when this guard drops. 801 self.release_lock(resume, lock); 802 if let (Some(pk), Some(items)) = (persist, parked) { 803 pk.submit(items); 804 } 805 eprintln!( 806 "aien-serve-http: omega: lock wait {lock_wait_ms} ms, prompt {} tok, {} reused from the previous turn, prefill {} ms, decode {} tok in {} ms", 807 o.prompt_tokens, o.reused_prompt_tokens, o.prefill_ms, o.emitted_tokens, o.decode_ms 808 ); 809 Ok(GenerateOutcome { 810 emitted_tokens: o.emitted_tokens, 811 finish: match o.finish { 812 omega::FinishReason::Stop => FinishReason::Stop, 813 omega::FinishReason::Length => FinishReason::Length, 814 omega::FinishReason::Cancelled => FinishReason::Cancelled, 815 // A constraint finished the output: complete, which HTTP clients read as "stop". 816 omega::FinishReason::Constraint => FinishReason::Stop, 817 }, 818 prefill_ms: o.prefill_ms, 819 decode_ms: o.decode_ms, 820 sampling: Some(sampling), 821 }) 822 } 823 824 fn persistence_status(&self) -> Option { 825 match &self.persist { 826 PersistState::Off => None, 827 PersistState::Refused(why) => { 828 Some(serde_json::json!({ "state": "refused", "reason": why, "refusals": 1 })) 829 } 830 PersistState::On(pk) => Some(pk.status_json()), 831 } 832 } 833 } 834 835 #[cfg(test)] 836 mod tests { 837 use super::*; 838 839 #[test] 840 fn queued_lock_waits_its_turn_and_gives_up_cleanly() { 841 let dir = std::env::temp_dir().join(format!("q38-lock-test-{}", std::process::id())); 842 std::fs::create_dir_all(&dir).unwrap(); 843 let path = dir.join("lock"); 844 let held = GpuLock::acquire_at(&path, Duration::from_secs(1)).unwrap(); 845 // Gives up while held, and leaves nothing behind once the holder lets go. 846 assert!(GpuLock::acquire_queued_at(&path, Duration::from_millis(100)).is_err()); 847 drop(held); 848 std::thread::sleep(Duration::from_millis(100)); 849 let again = 850 GpuLock::acquire_at(&path, Duration::from_millis(200)).expect("helper released"); 851 // Waits in the queue: the holder lets go after 300 ms, inside the 3 s wait. 852 let t = std::thread::spawn(move || { 853 std::thread::sleep(Duration::from_millis(300)); 854 drop(again); 855 }); 856 let t0 = Instant::now(); 857 let got = 858 GpuLock::acquire_queued_at(&path, Duration::from_secs(3)).expect("queued acquire"); 859 assert!(t0.elapsed() >= Duration::from_millis(250)); 860 t.join().unwrap(); 861 drop(got); 862 } 863 864 #[test] 865 fn gpu_lock_is_exclusive_and_released_on_drop() { 866 // Use a private path so the test never touches the hive's real lock. 867 let dir = std::env::temp_dir().join(format!("own30b-lock-test-{}", std::process::id())); 868 std::fs::create_dir_all(&dir).unwrap(); 869 let path = dir.join("lock"); 870 let open = || { 871 OpenOptions::new() 872 .read(true) 873 .write(true) 874 .create(true) 875 .truncate(false) 876 .open(&path) 877 .unwrap() 878 }; 879 let a = open(); 880 // SAFETY: valid descriptors, non-blocking flock. 881 assert_eq!( 882 unsafe { libc::flock(a.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 883 0 884 ); 885 let b = open(); 886 assert_ne!( 887 unsafe { libc::flock(b.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 888 0, 889 "second holder must be refused" 890 ); 891 drop(a); 892 assert_eq!( 893 unsafe { libc::flock(b.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 894 0, 895 "released on drop" 896 ); 897 drop(b); 898 let _ = std::fs::remove_dir_all(&dir); 899 } 900 901 #[test] 902 fn mem_available_reads_proc() { 903 assert!(mem_available_gb() > 0.0); 904 } 905 906 #[test] 907 fn prefill_mode_defaults_on_and_env_switches_off() { 908 assert_eq!( 909 PrefillMode::default(), 910 PrefillMode { 911 whole_prompt: true, 912 device_host: true 913 } 914 ); 915 assert_eq!( 916 PrefillMode::from_env(None, None).unwrap(), 917 PrefillMode::default() 918 ); 919 let m = PrefillMode::from_env(Some("0"), None).unwrap(); 920 assert!(!m.whole_prompt && m.device_host); 921 // The device router/combine lives inside the whole-prompt path: off with it. 922 assert_eq!( 923 m.effective(), 924 PrefillMode { 925 whole_prompt: false, 926 device_host: false 927 } 928 ); 929 let m = PrefillMode::from_env(Some("on"), Some("off")).unwrap(); 930 assert_eq!( 931 m.effective(), 932 PrefillMode { 933 whole_prompt: true, 934 device_host: false 935 } 936 ); 937 assert!(PrefillMode::from_env(Some("of"), None).is_err()); 938 assert!(parse_switch("--whole-prompt", "maybe").is_err()); 939 assert!(parse_switch("--whole-prompt", " TRUE ").unwrap()); 940 } 941 942 const GB: u64 = 1 << 30; 943 /// 30B at 131,072 positions: 48 layers x 256 MiB (live smaps, ledger L884). 944 const KV_BYTES: u64 = 48 * 256 * (1 << 20); 945 946 fn cold() -> WholePromptFootprint { 947 WholePromptFootprint { 948 on: true, 949 mirror_live: false, 950 scratch_tokens: 0, 951 kv_bytes: KV_BYTES, 952 chunk: 8192, 953 } 954 } 955 956 #[test] 957 fn mem_available_is_read_from_meminfo_text() { 958 let t = "MemTotal: `126000000` kB\nMemFree: 1 kB\nMemAvailable: `39000000` kB\nBuffers: 1 kB\n"; 959 assert_eq!(parse_mem_available(t), Some(39_000_000 * 1024)); 960 assert_eq!(parse_mem_available("MemTotal: 1 kB\n"), None); 961 assert_eq!(parse_mem_available("MemAvailable: lots kB\n"), None); 962 } 963 964 #[test] 965 fn the_live_incident_names_the_shortfall_without_a_zero_token_limit() { 966 // 14:24Z: a 66k-token prompt arrived with ~11 GB available and nothing warm yet. 967 // The mirror alone does not fit, so "send at most about 0 tokens" is not a limit a 968 // client can use. The door takes the classic path instead of 413ing forever. 969 let g = cold().growth(66_000); 970 let err = admit_growth(g, Some(11 * GB), 66_000).unwrap_err(); 971 assert!(err.contains("66000 tokens"), "{err}"); 972 assert!(err.contains("KV mirror"), "{err}"); 973 assert!(err.contains("6 GB must stay free"), "{err}"); 974 assert!( 975 !err.contains("about 0 tokens"), 976 "a zero token limit cannot warm the server: {err}" 977 ); 978 assert!(err.contains("retry when memory is free"), "{err}"); 979 assert_eq!( 980 admit_request(&cold(), Some(11 * GB), 4), 981 Ok(PrefillAdmit::Classic) 982 ); 983 assert_eq!( 984 admit_request(&cold(), Some(11 * GB), 66_000), 985 Ok(PrefillAdmit::Classic) 986 ); 987 let warm = WholePromptFootprint { 988 mirror_live: true, 989 scratch_tokens: 8192, 990 ..cold() 991 }; 992 assert_eq!( 993 admit_request(&warm, Some(11 * GB), 120_000), 994 Ok(PrefillAdmit::WholePrompt), 995 "once the mirror is live a chunked prompt adds nothing and is admitted" 996 ); 997 } 998 999 #[test] 1000 fn a_warm_server_still_refuses_scratch_it_cannot_pay_for() { 1001 let warm = WholePromptFootprint { 1002 mirror_live: true, 1003 scratch_tokens: 0, 1004 chunk: 0, 1005 ..cold() 1006 }; 1007 assert!(matches!( 1008 admit_request(&warm, Some(GB), 66_000), 1009 Err(ref e) if !e.contains("about 0 tokens") 1010 )); 1011 } 1012 1013 #[test] 1014 fn a_warm_server_admits_any_chunked_prompt_even_when_memory_is_low() { 1015 let warm = WholePromptFootprint { 1016 mirror_live: true, 1017 scratch_tokens: 8192, 1018 ..cold() 1019 }; 1020 assert_eq!(warm.growth(120_000), PrefillGrowth::default()); 1021 assert!(admit_growth(warm.growth(120_000), Some(7 * GB), 120_000).is_ok()); 1022 // Below the reserve too: the prefill adds nothing, so refusing it frees nothing. 1023 assert!(admit_growth(warm.growth(120_000), Some(GB), 120_000).is_ok()); 1024 } 1025 1026 #[test] 1027 fn admission_keeps_the_reserve_and_names_how_many_tokens_fit() { 1028 let g = cold().growth(8192); 1029 let need = g.total() + ADMIT_RESERVE_BYTES; 1030 assert!(admit_growth(g, Some(need), 8192).is_ok()); 1031 let err = admit_growth(g, Some(need - 1), 8192).unwrap_err(); 1032 assert!(err.contains("retry when memory is free"), "{err}"); 1033 // 19 GB free, mirror takes 12: (19 - 6 - 12) GB / 240 KiB per token. 1034 let err = admit_growth(g, Some(19 * GB), 8192).unwrap_err(); 1035 let fits = GB / SCRATCH_BYTES_PER_TOKEN; 1036 assert!(err.contains(&format!("about {fits} tokens")), "{err}"); 1037 } 1038 1039 #[test] 1040 fn unreadable_meminfo_and_a_switched_off_path_admit() { 1041 assert!(admit_growth(cold().growth(66_000), None, 66_000).is_ok()); 1042 let off = WholePromptFootprint { 1043 on: false, 1044 ..cold() 1045 }; 1046 assert_eq!(off.growth(66_000), PrefillGrowth::default()); 1047 assert!(admit_growth(off.growth(66_000), Some(GB), 66_000).is_ok()); 1048 } 1049 1050 fn greedy_one() -> GenerateParams { 1051 GenerateParams { 1052 max_new_tokens: 1, 1053 temperature: 0.0, 1054 top_p: 1.0, 1055 top_k: 0, 1056 seed: 1, 1057 stop_token_ids: Vec::new(), 1058 } 1059 } 1060 1061 fn host_door(tag: &str) -> (OmegaDoor, std::path::PathBuf) { 1062 let dir = std::env::temp_dir().join(format!( 1063 "admit-{tag}-{}-{}", 1064 std::process::id(), 1065 std::time::SystemTime::now() 1066 .duration_since(std::time::UNIX_EPOCH) 1067 .unwrap() 1068 .as_nanos() 1069 )); 1070 std::fs::create_dir_all(&dir).unwrap(); 1071 let path = dir.join("lock"); 1072 let engine = aien_inference_abi::qwen3_moe_omega::host_test_engine::engine( 1073 WeightFormat::Fp8All, 1074 256, 1075 ) 1076 .expect("tiny host engine"); 1077 let door = OmegaDoor::from_parts(engine, path.clone(), Duration::from_secs(5)); 1078 (door, path) 1079 } 1080 1081 #[test] 1082 fn cold_door_serves_and_a_warm_door_still_serves_on_the_same_tight_box() { 1083 let (mut door, _path) = host_door("cold"); 1084 let tight = 11 * GB; 1085 door.available_probe = Some(std::sync::Arc::new(move || Some(tight))); 1086 *door.footprint.lock().unwrap() = cold(); 1087 let prompt = [1u32, 2, 3, 4]; 1088 assert_eq!(door.decide(prompt.len()).unwrap(), PrefillAdmit::Classic); 1089 assert!( 1090 door.admit(&prompt).is_ok(), 1091 "the server's early admit must not 413 a cold box the classic path can serve" 1092 ); 1093 let got = door.generate(&prompt, &greedy_one(), &mut |_| true); 1094 assert!( 1095 got.is_ok(), 1096 "cold below the mirror must recover by serving, not 413 forever: {got:?}" 1097 ); 1098 *door.footprint.lock().unwrap() = WholePromptFootprint { 1099 mirror_live: true, 1100 scratch_tokens: 8192, 1101 ..cold() 1102 }; 1103 assert_eq!( 1104 door.decide(prompt.len()).unwrap(), 1105 PrefillAdmit::WholePrompt 1106 ); 1107 let again = door.generate(&[1, 2, 3, 5], &greedy_one(), &mut |_| true); 1108 assert!( 1109 again.is_ok(), 1110 "once warm the same tight box admits a chunked prompt: {again:?}" 1111 ); 1112 } 1113 1114 #[test] 1115 fn admission_sees_the_kv_payload_and_a_drop_during_the_lock_wait() { 1116 assert!( 1117 !crate::chip_reservation::inherited(), 1118 "this test needs a real flock; an inherited reservation skips the lock" 1119 ); 1120 let (mut door, path) = host_door("race"); 1121 // Warm mirror, no scratch yet, one pass: growth is the prompt scratch plus the reserve. 1122 // 20 GiB admits. The fetch's 8 GiB and the 8 GiB that disappear while the lock is waited 1123 // for, together, do not. Either drop alone still admits, so the check has to run after both. 1124 *door.footprint.lock().unwrap() = WholePromptFootprint { 1125 on: true, 1126 mirror_live: true, 1127 scratch_tokens: 0, 1128 kv_bytes: KV_BYTES, 1129 chunk: 0, 1130 }; 1131 let avail = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(20 * GB)); 1132 let fetched = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); 1133 door.available_probe = Some({ 1134 let avail = std::sync::Arc::clone(&avail); 1135 std::sync::Arc::new(move || Some(avail.load(Ordering::SeqCst))) 1136 }); 1137 door.fetch_probe = Some({ 1138 let avail = std::sync::Arc::clone(&avail); 1139 let fetched = std::sync::Arc::clone(&fetched); 1140 std::sync::Arc::new(move || { 1141 avail.fetch_sub(8 * GB, Ordering::SeqCst); 1142 fetched.store(true, Ordering::SeqCst); 1143 }) 1144 }); 1145 let held = GpuLock::acquire_at(&path, Duration::from_secs(2)).expect("test holds the lock"); 1146 let prompt: Vec = (0..200).map(|i| (i % 64) as u32).collect(); 1147 let params = greedy_one(); 1148 let got = std::thread::scope(|scope| { 1149 let worker = scope.spawn(|| door.generate(&prompt, ¶ms, &mut |_| true)); 1150 let start = Instant::now(); 1151 while !fetched.load(Ordering::SeqCst) { 1152 if start.elapsed() > Duration::from_secs(15) { 1153 drop(held); 1154 panic!("generate did not reach the KV fetch before taking the lock"); 1155 } 1156 std::thread::sleep(Duration::from_millis(10)); 1157 } 1158 avail.fetch_sub(8 * GB, Ordering::SeqCst); 1159 drop(held); 1160 worker.join().expect("generate thread") 1161 }); 1162 match got { 1163 Err(EngineError::MemoryExceeded(m)) => { 1164 assert!( 1165 m.contains("4.3 GB is available"), 1166 "admission must see the post-fetch, post-wait memory, not the earlier reading: {m}" 1167 ); 1168 } 1169 other => panic!("expected a 413 after the lock, got {other:?}"), 1170 } 1171 } 1172 1173 #[test] 1174 fn more_free_memory_never_refuses_a_prompt_a_tighter_box_serves() { 1175 let one_pass = WholePromptFootprint { chunk: 0, ..cold() }; 1176 let low = admit_request(&one_pass, Some(11 * GB), 66_000).unwrap(); 1177 let high = admit_request(&one_pass, Some(20 * GB), 66_000).unwrap(); 1178 assert_eq!(low, PrefillAdmit::Classic); 1179 assert!( 1180 matches!(high, PrefillAdmit::Classic | PrefillAdmit::WholePrompt), 1181 "20 GB refused a 66k one-pass prompt that 11 GB served: {high:?}" 1182 ); 1183 let warm = WholePromptFootprint { 1184 mirror_live: true, 1185 scratch_tokens: 0, 1186 chunk: 0, 1187 ..cold() 1188 }; 1189 for fp in [cold(), one_pass, warm] { 1190 for n in [4usize, 8192, 66_000] { 1191 let mut served = false; 1192 for gb in [1u64, 8, 11, 16, 20, 40, 80] { 1193 let ok = admit_request(&fp, Some(gb * GB), n).is_ok(); 1194 if served { 1195 assert!( 1196 ok, 1197 "{n} tokens served below {gb} GiB and refused at {gb} GiB" 1198 ); 1199 } 1200 served = ok; 1201 } 1202 } 1203 } 1204 } 1205 1206 #[test] 1207 fn admission_prices_the_uncached_suffix_not_the_whole_prompt() { 1208 assert_eq!(priced_tokens(66_000, 65_000), 1_000); 1209 assert_eq!(priced_tokens(66_000, 66_000), 1); 1210 assert_eq!(priced_tokens(66_000, 0), 66_000); 1211 let warm = WholePromptFootprint { 1212 mirror_live: true, 1213 scratch_tokens: 0, 1214 chunk: 0, 1215 ..cold() 1216 }; 1217 let suffix = priced_tokens(66_000, 65_000); 1218 let tight = Some(ADMIT_RESERVE_BYTES + suffix as u64 * SCRATCH_BYTES_PER_TOKEN); 1219 assert!(admit_request(&warm, tight, priced_tokens(66_000, 0)).is_err()); 1220 assert!(admit_request(&warm, tight, suffix).is_ok()); 1221 } 1222 1223 #[test] 1224 fn a_reused_prefix_is_not_priced_as_a_cold_prompt() { 1225 let (mut door, _) = host_door("reuse"); 1226 let prompt: Vec = (0..80).map(|i| (i % 64) as u32).collect(); 1227 door.available_probe = Some(std::sync::Arc::new(|| Some(80 * GB))); 1228 let first = door.generate(&prompt, &greedy_one(), &mut |_| true); 1229 assert!(first.is_ok(), "{first:?}"); 1230 let reused = door 1231 .engine 1232 .with_engine(|e| e.reusable_prefix(&prompt)) 1233 .unwrap(); 1234 assert_eq!(reused, prompt.len() - 1, "reused {reused}"); 1235 let tight = ADMIT_RESERVE_BYTES + 2 * SCRATCH_BYTES_PER_TOKEN; 1236 door.available_probe = Some(std::sync::Arc::new(move || Some(tight))); 1237 *door.footprint.lock().unwrap() = WholePromptFootprint { 1238 on: true, 1239 mirror_live: true, 1240 scratch_tokens: 0, 1241 kv_bytes: KV_BYTES, 1242 chunk: 0, 1243 }; 1244 assert!(door.admit(&prompt).is_ok(), "the uncached suffix must fit"); 1245 let second = door.generate(&prompt, &greedy_one(), &mut |_| true); 1246 assert!( 1247 second.is_ok(), 1248 "a reused prompt was priced as the full length: {second:?}" 1249 ); 1250 1251 let (mut fresh, _) = host_door("reuse-full"); 1252 fresh.available_probe = Some(std::sync::Arc::new(move || Some(tight))); 1253 *fresh.footprint.lock().unwrap() = WholePromptFootprint { 1254 on: true, 1255 mirror_live: true, 1256 scratch_tokens: 0, 1257 kv_bytes: KV_BYTES, 1258 chunk: 0, 1259 }; 1260 let refused = fresh.generate(&prompt, &greedy_one(), &mut |_| true); 1261 assert!( 1262 matches!(refused, Err(EngineError::MemoryExceeded(_))), 1263 "the same prompt with no prefix must be refused: {refused:?}" 1264 ); 1265 } 1266 1267 #[test] 1268 fn suspension_is_cleared_before_the_lock_is_released() { 1269 let (mut door, _) = host_door("drop-order"); 1270 let seen = std::sync::Arc::new(AtomicBool::new(true)); 1271 let vis = std::sync::Arc::clone(&door.suspend_visible); 1272 let seen_h = std::sync::Arc::clone(&seen); 1273 door.lock_release_hook = Some(std::sync::Arc::new(move || { 1274 seen_h.store(vis.load(Ordering::SeqCst), Ordering::SeqCst); 1275 })); 1276 door.available_probe = Some(std::sync::Arc::new(|| Some(11 * GB))); 1277 *door.footprint.lock().unwrap() = cold(); 1278 let got = door.generate(&[1, 2, 3, 4], &greedy_one(), &mut |_| true); 1279 assert!(got.is_ok(), "{got:?}"); 1280 assert!( 1281 !seen.load(Ordering::SeqCst), 1282 "the lock dropped while classic suspension was still set" 1283 ); 1284 } 1285 }