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/patches/3f34231201a31981 # 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 ## GitHub aien-dev/aien-sovereign-core-mv#246 (code only) closed derived `3f34231201a31981` #246 Imported from GitHub aien-dev/aien-sovereign-core-mv#246 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `6dbee7e3a8631985bd75580d8cf2da8c206df7a6` · Head `18eae365e640009074ecf0441782c53b43d05b31` ### Fetch it A git bundle of the pull request's head, 16161 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/3f34231201a31981.bundle -o 3f34231201a31981.bundle git fetch 3f34231201a31981.bundle refs/pull/246/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 246 18eae365e640009074ecf0441782c53b43d05b31 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":246,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/246","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:31Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index e5bb5905..2302676d 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:009593670dc7accc2b442a6a8c6f3b848ab73de4d6e61df57401bf4bf00b294a", - "compiled_at": "2026-10-06T23:54:32Z", + "compiled_at": "2026-10-07T00:19:21Z", "compiler": "crumb-compile/1", - "digest": "sha256:4ed9d62b3cff270611467090a1efaa16acea64916f49361d8fdab17d260409d6", + "digest": "sha256:957bfa1bb56ef9944da093bf2aea865dbe1124932e8470c4dd7704ff33734789", "evidence_files": 90, "evidence_root": "sha256:913405b594470a9dfda6998ea0386eba372f438bce4e9d05c062369a9f7b1e22", "files": 954, - "generated_at_commit": "e68f200ff7f60ea821590a06901ea534ccc52279", - "source_tree": "sha256:ccae4fb70742224a69ab9e1db58e8e02abd0f07f09f3972c6555b0d5ddec07ae" + "generated_at_commit": "de17cfae614885230fa033c86f6e17ed4e4e34dd", + "source_tree": "sha256:d5cd6e336634bc95f2aaf73f7e66a2ddf63d8ca7957ae49d2cef467ee2c2791d" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 2cbeab06..b69187b4 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "b51d47ac56083a63aa043fdbaaeaee6a65e87485d4b40a179b3fbc9726ab94db", - "last_commit": "8c5294c", + "digest": "a2a6a6d1d40496ec8caadef540d3ddfa3783b1a8c86bce80ddc18b4205331d9f", + "last_commit": "9a8298c", "name": "src", "purpose": "" } ], - "children_root": "sha256:0bcda6a58f2ed2c6bdaae3923cf34932c6ee003d18a72a4259afc6cd9998dbf7", - "compiled_at": "2026-10-06T23:10:12Z", + "children_root": "sha256:236d1ee979d722f3fca5ff35301e27e05835c7b9caa177cbea0d5f77e4f0a19c", + "compiled_at": "2026-10-07T00:19:21Z", "compiler": "crumb-compile/1", - "digest": "sha256:0309f5ed1dae40099bd9ce71d11c3fc07cd18b48d7ac1672e52e1e79562ac4e9", + "digest": "sha256:79d6c058a6cae2ef1e180918b84499fae8dc51508c175e4ae149955123c1b89f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 28, - "generated_at_commit": "f6cd19cfcd34e5b567e30307d70ee79c16b033fd", - "source_tree": "sha256:09f1b194fb0018c72cf64fb2465a0e9b3b58412931dad5007dcab199a1b86974" + "generated_at_commit": "de17cfae614885230fa033c86f6e17ed4e4e34dd", + "source_tree": "sha256:7c492cb18b9d18212a5e8c8b0665e533098624c80ffb4ce04a2de098d7117746" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index bf0d2c6e..7c5cfa18 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-06T23:10:12Z", + "compiled_at": "2026-10-07T00:19:21Z", "compiler": "crumb-compile/1", - "digest": "sha256:b51d47ac56083a63aa043fdbaaeaee6a65e87485d4b40a179b3fbc9726ab94db", + "digest": "sha256:a2a6a6d1d40496ec8caadef540d3ddfa3783b1a8c86bce80ddc18b4205331d9f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "f6cd19cfcd34e5b567e30307d70ee79c16b033fd", - "source_tree": "sha256:81bbf7425c009ba785b7af1be89d9db641acd73da7a05460f94f78d764eb96d1" + "generated_at_commit": "de17cfae614885230fa033c86f6e17ed4e4e34dd", + "source_tree": "sha256:0aa9afadef9bbdb28be1b22b893d53a45ce8d0d0544228cb698121b76da20365" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 22a3b6aa..f3639fd2 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1442,22 +1442,37 @@ pub async fn run_daemon_server() { }; // One KV for runtime and backend: the spine's block tables and the - // backend's K/V writes go to the same pooled manager. - let (spine, backend) = match aien_runtime::shared_kv::build_shared_kv_runtime( - weights, - tensor_backend, - sched_cfg, - aien_runtime::shared_kv::SharedKvSizing { - arena_capacity: 4096, - total_blocks: 8192, - }, - ) { - Ok(parts) => parts, - Err(fatal) => { - eprintln!("Fatal: shared KV pool: {}", fatal.red().bold()); + // backend's K/V writes go to the same pooled manager. The pool is sized + // from the loaded model's config and declared context, and the host's + // MemAvailable is checked before it is allocated (#239). + let gpu_native = aien_inference_abi::OmegaGb10Backend::new().is_available(); + let (spine, backend, _kv_plan) = + match aien_runtime::shared_kv::build_shared_kv_runtime_for_model( + weights, + tensor_backend, + sched_cfg, + 4096, + &aien_runtime::shared_kv::read_mem_available, + ) { + Ok(parts) => parts, + Err(fatal) => { + eprintln!("Fatal: shared KV pool: {}", fatal.red().bold()); + std::process::exit(1); + } + }; + // Open the GPU session before serving, with a bounded retry, so a failed + // channel open is a clear refusal with status and free memory per attempt + // instead of the strict-fallback panic at warm-up (#239, #236). + if gpu_native { + if let Err(fatal) = aien_inference_abi::open_gpu_session_with_retry( + aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS, + aien_inference_abi::GPU_SESSION_RETRY_DELAY, + &aien_runtime::shared_kv::read_mem_available, + ) { + eprintln!("Fatal: {}", fatal.red().bold()); std::process::exit(1); } - }; + } let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path); println!(" Backend: {}", backend_label.green()); diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 770a6d29..c5d643a4 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -32,7 +32,10 @@ pub use checkpoint::*; pub use model_dir::{load_model_config, model_config_from_hf_json, model_id_for_dir}; pub use moe_plan::*; pub use mojo_backend::*; -pub use omega_backend::{omega_backend_selected, OmegaGb10Backend, GPU_BACKEND_ENV}; +pub use omega_backend::{ + omega_backend_selected, open_gpu_session_with_retry, retry_bounded, OmegaGb10Backend, + SessionAttemptError, GPU_BACKEND_ENV, GPU_SESSION_OPEN_ATTEMPTS, GPU_SESSION_RETRY_DELAY, +}; pub use qwen3_coder::*; pub use qwen3_moe::*; pub use qwen3_serve::*; diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 430633d3..10da47ac 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -757,6 +757,125 @@ impl TensorBackend for OmegaGb10Backend { } } +// ---- bounded GPU session open (issue #239, diagnostics for #236) ---- + +/// Attempts the daemon makes to open the GPU session before it refuses to start. +pub const GPU_SESSION_OPEN_ATTEMPTS: u32 = 3; + +/// Pause between two session-open attempts. +pub const GPU_SESSION_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(500); + +/// Why one session-open attempt failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionAttemptError { + /// Return code and omega stage, as the chip-error log prints them. + pub message: String, + /// True once omega has latched the process (every later chip call fails), so a + /// further attempt cannot succeed and is not made. + pub latched: bool, +} + +/// Runs `attempt(n)` for `n = 1..=attempts` (at least once) until one succeeds and +/// returns its value with the attempt number. Each failure goes to `on_failure` +/// (the caller logs it); `pause(n)` runs between failed attempt `n` and the next. A +/// latched failure stops at once. Never loops past `attempts`. +pub fn retry_bounded( + attempts: u32, + mut attempt: impl FnMut(u32) -> Result, + mut on_failure: impl FnMut(u32, u32, &SessionAttemptError), + mut pause: impl FnMut(u32), +) -> Result<(T, u32), String> { + let attempts = attempts.max(1); + let mut last = String::new(); + for n in 1..=attempts { + match attempt(n) { + Ok(v) => return Ok((v, n)), + Err(e) => { + on_failure(n, attempts, &e); + if e.latched { + return Err(format!( + "GPU session open failed on attempt {n}/{attempts} and omega latched the process (not retried): {}", + e.message + )); + } + last = e.message; + if n < attempts { + pause(n); + } + } + } + } + Err(format!( + "GPU session did not open after {attempts} attempts; last error: {last}" + )) +} + +fn fmt_mem(bytes: Option) -> String { + match bytes { + Some(b) => format!("{b} bytes ({:.2} GiB)", b as f64 / (1u64 << 30) as f64), + None => "unknown".to_string(), + } +} + +/// Opens the GPU session before serving, with up to `attempts` tries `delay` apart. +/// +/// omega opens its device and channel lazily on the first chip call, and a failed +/// open leaves the session closed but not latched (omega c0369e6 +/// src/omega_gpu_session.c:101-109: `m16_native_create_channel` failure closes and +/// returns NULL without setting `g_blocked`), so the next call opens again. The +/// probe is one 1 x 128 rmsnorm called on `aien_omega_gpu` directly, outside the +/// `TensorBackend` accounting, so a failure here is a clear start-up refusal +/// instead of the strict-fallback panic at warm-up (#236). Every attempt logs its +/// number, the omega status and stage, and `MemAvailable` from `mem_available`. +/// Returns the attempt number that opened the session. +pub fn open_gpu_session_with_retry( + attempts: u32, + delay: std::time::Duration, + mem_available: &dyn Fn() -> Option, +) -> Result { + if !aien_omega_gpu::is_native() { + return Err( + "GPU session open: the Omega GPU engine is not linked (stub build)".to_string(), + ); + } + const PROBE_DIM: usize = 128; // omega rmsnorm needs dim % 128 == 0 + let ones = [1.0f32; PROBE_DIM]; + let (_, n) = retry_bounded( + attempts, + |_| { + let mut out = [0.0f32; PROBE_DIM]; + aien_omega_gpu::rmsnorm_f32(1, PROBE_DIM, &ones, &ones, 1e-5, &mut out) + .map(|_| ()) + .map_err(|e| { + let stage = aien_omega_gpu::last_error(); + SessionAttemptError { + message: if stage.is_empty() { + e.to_string() + } else { + format!("{e} (stage: {stage})") + }, + latched: aien_omega_gpu::is_blocked(), + } + }) + }, + |n, of, e| { + eprintln!( + "OMEGA_BACKEND GPU session open attempt {n}/{of} failed: {}; latched={}; MemAvailable {}", + e.message, + e.latched, + fmt_mem(mem_available()) + ) + }, + |_| std::thread::sleep(delay), + )?; + println!( + " GPU session: open on attempt {n}/{} (MemAvailable {})", + attempts.max(1), + fmt_mem(mem_available()) + ); + Ok(n) +} + #[cfg(test)] mod tests { use super::*; @@ -950,4 +1069,91 @@ mod tests { b[999] = 2.0; assert_ne!(fingerprint(&a), fingerprint(&b)); } + + fn fail_msg(n: u32, latched: bool) -> SessionAttemptError { + SessionAttemptError { + message: format!("omega_gpu rc=-4 (CHIP_FAIL) try {n}"), + latched, + } + } + + #[test] + fn retry_stops_at_the_bound_and_logs_every_attempt() { + let (mut calls, mut logged, mut pauses) = (0u32, Vec::new(), Vec::new()); + let err = retry_bounded::<()>( + 3, + |n| { + calls += 1; + Err(fail_msg(n, false)) + }, + |n, of, e| logged.push(format!("{n}/{of}: {}", e.message)), + |n| pauses.push(n), + ) + .unwrap_err(); + assert_eq!(calls, 3); + assert_eq!(pauses, vec![1, 2]); + assert_eq!(logged.len(), 3); + assert!(logged[2].starts_with("3/3")); + assert!( + err.contains("after 3 attempts") && err.contains("try 3"), + "{err}" + ); + } + + #[test] + fn retry_returns_the_attempt_that_succeeded() { + let mut pauses = 0; + let r = retry_bounded( + 3, + |n| { + if n < 2 { + Err(fail_msg(n, false)) + } else { + Ok(n * 10) + } + }, + |_, _, _| {}, + |_| pauses += 1, + ); + assert_eq!(r, Ok((20, 2))); + assert_eq!(pauses, 1); + } + + #[test] + fn retry_does_not_repeat_a_latched_failure_and_runs_at_least_once() { + let mut calls = 0; + let err = retry_bounded::<()>( + 3, + |n| { + calls += 1; + Err(fail_msg(n, true)) + }, + |_, _, _| {}, + |_| panic!("no pause after a latched failure"), + ) + .unwrap_err(); + assert_eq!(calls, 1); + assert!(err.contains("latched") && err.contains("1/3"), "{err}"); + + let mut zero_calls = 0; + let _ = retry_bounded::<()>( + 0, + |n| { + zero_calls += 1; + Err(fail_msg(n, false)) + }, + |_, _, _| {}, + |_| {}, + ); + assert_eq!(zero_calls, 1); + } + + #[test] + fn session_open_refuses_cleanly_in_a_stub_build() { + if aien_omega_gpu::is_native() { + return; // the native path is verified on the chip, not here + } + let err = open_gpu_session_with_retry(3, std::time::Duration::ZERO, &|| None).unwrap_err(); + assert!(err.contains("not linked"), "{err}"); + } } diff --git a/crates/aien-runtime/src/shared_kv.rs b/crates/aien-runtime/src/shared_kv.rs index 3f49ce8c..de5fa39d 100644 --- a/crates/aien-runtime/src/shared_kv.rs +++ b/crates/aien-runtime/src/shared_kv.rs @@ -68,3 +68,394 @@ pub fn build_shared_kv_runtime( NativeTransformerBackend::with_shared_kv_and_backend(weights, tensor_backend, kv_manager); Ok((spine, backend)) } + +/// Element type of the shared pool. `build_model_kv_manager` lays the pool out +/// in this dtype, and [`KvPoolPlan`] prices it with the same value. +pub const SHARED_KV_DTYPE: KvDType = KvDType::Fp32; + +/// The daemon's KV pool, sized from the loaded model (issue #239). +/// +/// Before #239 the daemon asked for a fixed 8192 blocks for every model. With +/// the 16-token blocks of `model_dir.rs` that is 131072 tokens, which happens to +/// be Llama-3.2-1B's `max_position_embeddings`, but it priced every other model +/// at 131072 tokens too (SmolLM2-1.7B: 48 GiB of Fp32 KV for a model whose +/// context is 8192 tokens). The plan now takes the declared context budget from +/// the model itself (`ModelConfig::max_sequence_length`, i.e. config.json +/// `max_position_embeddings`) and derives +/// `bytes = blocks * block_size * num_layers * num_kv_heads * head_dim * 2 (K and V) * dtype bytes`, +/// with `blocks = ceil(context / block_size)`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KvPoolPlan { + /// Declared context budget in tokens (where it came from: `context_source`). + pub context_tokens: usize, + /// Where `context_tokens` was taken from, for the startup log. + pub context_source: &'static str, + pub block_size: usize, + pub total_blocks: usize, + pub num_layers: usize, + pub num_kv_heads: usize, + pub head_dim: usize, + pub dtype_bytes: usize, + /// K plus V bytes for one token across all layers. + pub bytes_per_token: usize, + /// Bytes of the whole pool (`total_blocks * block_size * bytes_per_token`). + pub total_bytes: usize, +} + +const GIB: f64 = (1u64 << 30) as f64; + +/// Bytes as GiB with two decimals, for logs and refusals. +pub fn fmt_gib(bytes: u64) -> String { + format!("{:.2} GiB", bytes as f64 / GIB) +} + +impl KvPoolPlan { + /// Plan for `cfg` at the model's own declared context (`max_sequence_length`). + pub fn for_model(cfg: &aien_inference_abi::ModelConfig) -> Result { + Self::for_context( + cfg, + cfg.max_sequence_length, + "model max_sequence_length (config.json max_position_embeddings)", + ) + } + + /// Plan for `cfg` at an explicit context budget. Every product is checked, so a + /// config that would overflow `usize` is refused instead of wrapping. + pub fn for_context( + cfg: &aien_inference_abi::ModelConfig, + context_tokens: usize, + context_source: &'static str, + ) -> Result { + let named = [ + ("context_tokens", context_tokens), + ("block_size", cfg.block_size), + ("num_layers", cfg.num_layers), + ("num_kv_heads", cfg.num_kv_heads), + ("head_dim", cfg.head_dim), + ]; + if let Some((name, _)) = named.iter().find(|(_, v)| *v == 0) { + return Err(format!("KV pool plan: {name} is 0")); + } + // Fp32 is 4 bytes; the f32 accessor is exact for every whole-byte dtype. + let dtype_bytes = SHARED_KV_DTYPE.bytes_per_element() as usize; + let overflow = || "KV pool plan: size overflows usize".to_string(); + let bytes_per_token = 2usize + .checked_mul(cfg.num_layers) + .and_then(|v| v.checked_mul(cfg.num_kv_heads)) + .and_then(|v| v.checked_mul(cfg.head_dim)) + .and_then(|v| v.checked_mul(dtype_bytes)) + .ok_or_else(overflow)?; + let total_blocks = context_tokens.div_ceil(cfg.block_size); + let total_bytes = total_blocks + .checked_mul(cfg.block_size) + .and_then(|v| v.checked_mul(bytes_per_token)) + .ok_or_else(overflow)?; + Ok(Self { + context_tokens, + context_source, + block_size: cfg.block_size, + total_blocks, + num_layers: cfg.num_layers, + num_kv_heads: cfg.num_kv_heads, + head_dim: cfg.head_dim, + dtype_bytes, + bytes_per_token, + total_bytes, + }) + } + + /// The pool config `build_model_kv_manager` builds for this plan. + pub fn pool_config(&self) -> KvPoolConfig { + KvPoolConfig::for_model( + self.total_blocks, + self.block_size, + self.num_layers, + self.num_kv_heads, + self.head_dim, + SHARED_KV_DTYPE, + ) + } + + /// One startup log line: size in bytes and GiB plus every derived parameter. + pub fn log_line(&self) -> String { + format!( + "KV pool: {} bytes ({}) = {} blocks x {} tokens x {} layers x {} kv heads x {} head_dim x 2 (K,V) x {} bytes; context {} tokens from {}", + self.total_bytes, + fmt_gib(self.total_bytes as u64), + self.total_blocks, + self.block_size, + self.num_layers, + self.num_kv_heads, + self.head_dim, + self.dtype_bytes, + self.context_tokens, + self.context_source, + ) + } +} + +/// `MemAvailable` from the text of `/proc/meminfo`, in bytes (the file reports kB). +pub fn parse_mem_available(meminfo: &str) -> Option { + meminfo.lines().find_map(|line| { + let rest = line.strip_prefix("MemAvailable:")?; + let mut parts = rest.split_whitespace(); + let value: u64 = parts.next()?.parse().ok()?; + match parts.next() { + Some("kB") => value.checked_mul(1024), + _ => None, + } + }) +} + +/// `MemAvailable` of this host in bytes, or `None` where `/proc/meminfo` is absent +/// or has no parsable `MemAvailable` line. +pub fn read_mem_available() -> Option { + std::fs::read_to_string("/proc/meminfo") + .ok() + .as_deref() + .and_then(parse_mem_available) +} + +/// Refuses the pool when the host reports less available memory than it needs. +/// `available == None` (no `/proc/meminfo`) cannot be checked and passes; the +/// caller logs that the check was skipped. +pub fn check_kv_memory(requested: u64, available: Option) -> Result<(), String> { + match available { + Some(avail) if requested > avail => Err(format!( + "KV pool needs {requested} bytes ({}) but MemAvailable is {avail} bytes ({}); refusing to allocate", + fmt_gib(requested), + fmt_gib(avail), + )), + _ => Ok(()), + } +} + +/// Daemon planning step (#239): plans the pool for `cfg`, logs the plan, and +/// checks `MemAvailable` (read through `mem_available`) before anything is +/// allocated. Allocates nothing itself. +pub fn plan_checked_model_kv( + cfg: &aien_inference_abi::ModelConfig, + mem_available: &dyn Fn() -> Option, +) -> Result { + let plan = KvPoolPlan::for_model(cfg)?; + println!(" {}", plan.log_line()); + let available = mem_available(); + match available { + Some(avail) => println!( + " KV pool memory check: needs {} bytes ({}), MemAvailable {} bytes ({})", + plan.total_bytes, + fmt_gib(plan.total_bytes as u64), + avail, + fmt_gib(avail) + ), + None => println!(" KV pool memory check: skipped (no MemAvailable in /proc/meminfo)"), + } + check_kv_memory(plan.total_bytes as u64, available)?; + Ok(plan) +} + +/// Daemon path (#239): [`plan_checked_model_kv`], then builds the spine and +/// backend over the one pooled manager sized by the plan. +pub fn build_shared_kv_runtime_for_model( + weights: TransformerWeights, + tensor_backend: Arc, + scheduler_config: SchedulerConfig, + arena_capacity: usize, + mem_available: &dyn Fn() -> Option, +) -> Result<(AienRuntimeSpine, NativeTransformerBackend, KvPoolPlan), String> { + let plan = plan_checked_model_kv(&weights.config, mem_available)?; + let (spine, backend) = build_shared_kv_runtime( + weights, + tensor_backend, + scheduler_config, + SharedKvSizing { + arena_capacity, + total_blocks: plan.total_blocks, + }, + )?; + Ok((spine, backend, plan)) +} + +#[cfg(test)] +mod tests { + use super::*; + use aien_inference_abi::model_config_from_hf_json; + + /// Blocks the daemon asked for before #239 (aien-cli/src/commands.rs, + /// `SharedKvSizing { total_blocks: 8192 }`, sovereign-core 328a7e9). + const OLD_FIXED_DAEMON_BLOCKS: usize = 8192; + + /// unsloth/Llama-3.2-1B-Instruct config.json, snapshot 5a8abab (the KV-relevant + /// fields as on disk; same text as the model_dir.rs fixture). + const LLAMA32_1B_CONFIG: &str = r#"{ + "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0, + "bos_token_id": 128000, "eos_token_id": 128009, "head_dim": 64, "hidden_act": "silu", + "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 8192, + "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama", + "num_attention_heads": 32, "num_hidden_layers": 16, "num_key_value_heads": 8, + "pad_token_id": 128004, "pretraining_tp": 1, "rms_norm_eps": 1e-05, + "rope_scaling": {"factor": 32.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, + "original_max_position_embeddings": 8192, "rope_type": "llama3"}, + "rope_theta": 500000.0, "tie_word_embeddings": true, "torch_dtype": "bfloat16", + "vocab_size": 128256 +}"#; + + /// HuggingFaceTB/SmolLM2-1.7B-Instruct config.json, revision 31b70e2e (the + /// fields this engine reads, as on disk; transformers.js block dropped). + const SMOLLM2_17B_CONFIG: &str = r#"{ + "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0, + "bos_token_id": 1, "eos_token_id": 2, "hidden_act": "silu", "hidden_size": 2048, + "initializer_range": 0.02, "intermediate_size": 8192, "max_position_embeddings": 8192, + "mlp_bias": false, "model_type": "llama", "num_attention_heads": 32, + "num_hidden_layers": 24, "num_key_value_heads": 32, "pad_token_id": 2, + "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 130000, + "tie_word_embeddings": true, "torch_dtype": "bfloat16", "use_cache": true, + "vocab_size": 49152 +}"#; + + fn cfg(id: &str, json: &str) -> aien_inference_abi::ModelConfig { + model_config_from_hf_json(id, json, None).expect("config.json parses") + } + + fn old_fixed_bytes(c: &aien_inference_abi::ModelConfig) -> usize { + KvPoolConfig::for_model( + OLD_FIXED_DAEMON_BLOCKS, + c.block_size, + c.num_layers, + c.num_kv_heads, + c.head_dim, + KvDType::Fp32, + ) + .total_bytes() + } + + #[test] + fn llama32_1b_plan_is_byte_identical_to_the_old_fixed_pool() { + let c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG); + let plan = KvPoolPlan::for_model(&c).unwrap(); + assert_eq!(plan.context_tokens, 131_072); + assert_eq!(plan.block_size, 16); + assert_eq!( + (plan.num_layers, plan.num_kv_heads, plan.head_dim), + (16, 8, 64) + ); + assert_eq!(plan.total_blocks, OLD_FIXED_DAEMON_BLOCKS); + // 2 * 16 * 8 * 64 * 4 + assert_eq!(plan.bytes_per_token, 65_536); + assert_eq!(plan.total_bytes, 8_589_934_592); // 8.00 GiB + assert_eq!(plan.total_bytes, old_fixed_bytes(&c)); + assert_eq!(plan.total_bytes, plan.pool_config().total_bytes()); + } + + #[test] + fn smollm2_plan_is_sized_from_its_own_context() { + let c = cfg("HuggingFaceTB/SmolLM2-1.7B-Instruct", SMOLLM2_17B_CONFIG); + let plan = KvPoolPlan::for_model(&c).unwrap(); + assert_eq!(plan.context_tokens, 8192); + assert_eq!( + (plan.num_layers, plan.num_kv_heads, plan.head_dim), + (24, 32, 64) + ); + assert_eq!(plan.total_blocks, 512); + // 2 * 24 * 32 * 64 * 4 + assert_eq!(plan.bytes_per_token, 393_216); + assert_eq!(plan.total_bytes, 3_221_225_472); // 3.00 GiB + assert_eq!(plan.total_bytes, plan.pool_config().total_bytes()); + // The old fixed pool was 16x larger: 48.00 GiB (51.5 GB). + assert_eq!(old_fixed_bytes(&c), 51_539_607_552); + assert_eq!(old_fixed_bytes(&c), 16 * plan.total_bytes); + } + + #[test] + fn plan_rounds_a_partial_block_up_and_refuses_zero_or_overflow() { + let mut c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG); + let plan = KvPoolPlan::for_context(&c, 17, "test").unwrap(); + assert_eq!(plan.total_blocks, 2); + assert_eq!(plan.total_bytes, 2 * 16 * 65_536); + assert!(KvPoolPlan::for_context(&c, 0, "test") + .unwrap_err() + .contains("context_tokens is 0")); + c.num_layers = usize::MAX / 2; + assert!(KvPoolPlan::for_model(&c).unwrap_err().contains("overflow")); + } + + #[test] + fn log_line_names_bytes_gib_and_every_parameter() { + let c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG); + let line = KvPoolPlan::for_model(&c).unwrap().log_line(); + for want in [ + "8589934592 bytes", + "8.00 GiB", + "8192 blocks", + "16 tokens", + "16 layers", + "8 kv heads", + "64 head_dim", + "4 bytes", + "context 131072 tokens", + "max_position_embeddings", + ] { + assert!(line.contains(want), "{want:?} missing from {line:?}"); + } + } + + #[test] + fn mem_available_parses_kb_and_rejects_garbage() { + let meminfo = + "MemTotal: 130000000 kB\nMemFree: 1000 kB\nMemAvailable: 62000000 kB\n"; + assert_eq!(parse_mem_available(meminfo), Some(62_000_000 * 1024)); + assert_eq!(parse_mem_available("MemTotal: 1 kB\n"), None); + assert_eq!(parse_mem_available("MemAvailable: x kB\n"), None); + assert_eq!(parse_mem_available("MemAvailable: 5\n"), None); + } + + #[test] + fn memory_check_refuses_with_requested_and_available_bytes() { + let err = check_kv_memory(3_221_225_472, Some(1_073_741_824)).unwrap_err(); + assert!(err.contains("3221225472 bytes (3.00 GiB)"), "{err}"); + assert!(err.contains("1073741824 bytes (1.00 GiB)"), "{err}"); + assert!(err.contains("refusing"), "{err}"); + assert!(check_kv_memory(10, Some(10)).is_ok()); + assert!(check_kv_memory(u64::MAX, None).is_ok()); + } + + fn tiny_config() -> aien_inference_abi::ModelConfig { + aien_inference_abi::ModelConfig { + model_id: "kv239-tiny".to_string(), + max_sequence_length: 40, + block_size: 16, + num_layers: 2, + num_heads: 4, + head_dim: 16, + num_kv_heads: 2, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 64, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), + } + } + + #[test] + fn daemon_plan_refuses_before_allocating_and_sizes_the_manager() { + // Exercises the planning, memory check and pooled manager without building a + // spine: a spine creates a RuntimeController, which reads the process-wide + // AIEN_RUNTIME_STATE_DIR that other tests in this crate point at temp dirs. + let cfg = tiny_config(); + let err = plan_checked_model_kv(&cfg, &|| Some(1)).unwrap_err(); + assert!(err.contains("refusing"), "{err}"); + + let plan = plan_checked_model_kv(&cfg, &|| None).expect("no meminfo: check skipped"); + // ceil(40 / 16) = 3 blocks of 16 tokens * (2 * 2 * 2 * 16 * 4) bytes per token. + assert_eq!(plan.total_blocks, 3); + assert_eq!(plan.total_bytes, 3 * 16 * 512); + + let weights = TransformerWeights::reference_test_weights(&cfg); + let mgr = build_model_kv_manager(&weights, plan.total_blocks).expect("pool built"); + assert_eq!(mgr.read().total_block_count(), 3); + assert_eq!(plan.pool_config().total_bytes(), plan.total_bytes); + } +} ```