From 07c3dfffbd84fd5b16484b725c48214e5bc801ca Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 20:15:52 -0500 Subject: [PATCH 1/7] RED: omega serving-reservation bindings, bounds sizing, and a test that the Qwen3 GB10 product path reserves (stub makes no call: 3 of 4 fail) Part of #277. omega.lock moves 01f6a74 -> b980783 (omega#333 reservation). Co-Authored-By: Claude Opus 5.5 --- crates/aien-inference-abi/src/gb10_serving.rs | 25 +++ crates/aien-inference-abi/src/lib.rs | 1 + .../tests/gb10_serving_reservation.rs | 111 ++++++++++++++ crates/aien-omega-gpu/src/ffi.rs | 21 +++ crates/aien-omega-gpu/src/lib.rs | 143 ++++++++++++++++++ omega.lock | 2 +- 6 files changed, 302 insertions(+), 1 deletion(-) create mode 100644 crates/aien-inference-abi/src/gb10_serving.rs create mode 100644 crates/aien-inference-abi/tests/gb10_serving_reservation.rs diff --git a/crates/aien-inference-abi/src/gb10_serving.rs b/crates/aien-inference-abi/src/gb10_serving.rs new file mode 100644 index 00000000..bc71ea0a --- /dev/null +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -0,0 +1,25 @@ +//! STUB (red run): the product path makes no serving reservation call. +use aien_abi_core::ModelConfig; +use aien_omega_gpu::{ServingBounds, ServingBytes}; + +pub struct ServingLimits { + pub context_tokens: usize, + pub max_batch_rows: usize, + pub prefill_chunk_rows: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServingReservation { + pub bounds: ServingBounds, + pub bytes: ServingBytes, +} + +pub fn reserve_gb10_serving_with( + _config: &ModelConfig, + _limits: &ServingLimits, + _gpu_native: bool, + _qwen3_opted_in: bool, + _reserve: &dyn Fn(&ServingBounds) -> Result<(), String>, +) -> Result, String> { + Ok(None) +} diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 3ef89006..8de3ba18 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize}; pub mod backend; pub mod capsule; pub mod checkpoint; +pub mod gb10_serving; pub mod model_dir; pub mod moe_plan; pub mod mojo_backend; diff --git a/crates/aien-inference-abi/tests/gb10_serving_reservation.rs b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs new file mode 100644 index 00000000..b3315a68 --- /dev/null +++ b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs @@ -0,0 +1,111 @@ +//! sovereign-core#277 (cut toward it, not a fix): when the daemon serves Qwen3 on the GB10 +//! (the already opt-in path), start-up reserves the serving buffers once, from declared +//! bounds, and refuses to serve by name when omega refuses. CPU only: the reservation call is +//! injected, nothing touches a driver. +use aien_inference_abi::gb10_serving::{reserve_gb10_serving_with, ServingLimits}; +use aien_inference_abi::model_config_from_hf_json; +use aien_omega_gpu::ServingBounds; +use std::cell::RefCell; +use std::path::PathBuf; + +fn qwen3_4b() -> aien_inference_abi::ModelConfig { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("qwen3-4b-instruct-2507-config"); + let cfg = std::fs::read_to_string(dir.join("config.json")).unwrap(); + let gen = std::fs::read_to_string(dir.join("generation_config.json")).unwrap(); + model_config_from_hf_json("Qwen/Qwen3-4B-Instruct-2507", &cfg, Some(&gen)).unwrap() +} + +/// The daemon's declared limits (aien-cli run_daemon_server: max_batch_size 256, prefill chunk +/// 128, arena 4096), with the KV pool planned for 4096 tokens. +fn daemon_limits() -> ServingLimits { + ServingLimits { + context_tokens: 4096, + max_batch_rows: 256, + prefill_chunk_rows: 128, + } +} + +#[test] +fn qwen3_on_gb10_reserves_once_before_serving_with_the_declared_bounds() { + let calls: RefCell> = RefCell::new(Vec::new()); + let got = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &|b| { + calls.borrow_mut().push(*b); + Ok(()) + }) + .expect("reserved") + .expect("Qwen3 on GB10 must reserve"); + let calls = calls.into_inner(); + assert_eq!(calls.len(), 1, "exactly one reservation call"); + let b = calls[0]; + assert_eq!(got.bounds, b); + assert_eq!((b.num_q_heads, b.num_kv_heads, b.head_dim), (32, 8, 128)); + assert_eq!(b.max_context, 4096); + assert_eq!( + b.max_seqs, 1, + "the GB10 backend runs attention one sequence at a time" + ); + assert_eq!(b.kv_block_size as usize, qwen3_4b().block_size); + assert_eq!( + b.max_rows, 256, + "decode batch rows (256) exceed the prefill chunk (128)" + ); + assert_eq!(b.max_k, 9728, "down_proj input is the intermediate size"); + assert_eq!(b.max_n_one_row, 151936, "the logits projection"); + assert!(b.max_n >= 9728); + assert!( + b.kernel_slots >= 21, + "21 distinct matmul shapes for Qwen3-4B (design note)" + ); + assert!(got.bytes.total() > 0); +} + +#[test] +fn context_is_the_smaller_of_the_kv_plan_and_the_attention_limit() { + let seen = RefCell::new(Vec::new()); + let rec = |b: &ServingBounds| { + seen.borrow_mut().push(b.max_context); + Ok(()) + }; + let mut l = daemon_limits(); + l.context_tokens = 2048; + reserve_gb10_serving_with(&qwen3_4b(), &l, true, true, &rec).unwrap(); + l.context_tokens = 262144; // the model's own declared context: omega's f32 attention stops at 4096 + reserve_gb10_serving_with(&qwen3_4b(), &l, true, true, &rec).unwrap(); + assert_eq!(*seen.borrow(), vec![2048, 4096]); +} + +#[test] +fn a_refusal_stops_serving_by_name_with_no_fallback() { + let err = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &|_| { + Err("omega_gpu rc=-4 (CHIP_FAIL) (stage: nvrm_alloc scratch)".to_string()) + }) + .expect_err("a refused reservation must refuse to serve"); + assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}"); + assert!(err.contains("CHIP_FAIL"), "names omega's reason: {err}"); + assert!(err.contains("sovereign-core#277"), "{err}"); + assert!(err.contains("no on-demand fallback"), "{err}"); +} + +#[test] +fn nothing_changes_off_the_opt_in_qwen3_gb10_path() { + let never = |_: &ServingBounds| -> Result<(), String> { panic!("must not reserve") }; + // not native (CPU daemon): no call + assert_eq!( + reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), false, true, &never).unwrap(), + None + ); + // default refusal still in force (no opt-in): the reservation is not what serves it + assert_eq!( + reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, false, &never).unwrap(), + None + ); + // a non-Qwen3 model on the GB10 is untouched + let mut llama = qwen3_4b(); + llama.qk_norm = false; + assert_eq!( + reserve_gb10_serving_with(&llama, &daemon_limits(), true, true, &never).unwrap(), + None + ); +} diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index 2a94bb43..2510cf92 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -144,6 +144,17 @@ extern "C" { // -1 above OMEGA_GPU_SESSION_MAX_SPIN_US with the setting unchanged (omega#328). pub fn omega_gpu_session_set_spin_us(us: u32) -> c_int; pub fn omega_gpu_session_spin_us() -> u32; + // omega b980783 `src/omega_gpu_matmul_api.h` (opt-in serving reservation, omega#333): activation and + // result staging for calls of up to max_rows rows plus a deeper kernel cache. 0 on success, else an + // OMEGA_GPU_MATMUL_* code (omega_gpu_matmul_last_error() has the text). + pub fn omega_gpu_matmul_reserve( + max_rows: u32, + max_k: u32, + max_n: u32, + max_n_one_row: u32, + kernel_slots: u32, + ) -> c_int; + pub fn omega_gpu_matmul_unreserve(); } // ---- omega `src/omega_gpu_elementwise_api.h` (FB-1 cut 4, pinned 2636409) ---- @@ -360,4 +371,14 @@ extern "C" { ) -> c_int; pub fn omega_gpu_attention_rc_name(rc: c_int) -> *const c_char; pub fn omega_gpu_attention_last_error() -> *const c_char; + // omega b980783 `src/omega_gpu_attention_api.h` (opt-in serving reservation, omega#333). + pub fn omega_gpu_attention_reserve( + max_context: u32, + max_seqs: u32, + num_q_heads: u32, + num_kv_heads: u32, + head_dim: u32, + kv_block_size: u32, + ) -> c_int; + pub fn omega_gpu_attention_unreserve(); } diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 02b40887..9963da68 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -883,6 +883,149 @@ fn check_pool(pool: &[u8], layout: &OmegaGpuKvLayout) -> Result<(), OmegaGpuErro Ok(()) } +// ---- opt-in serving reservation (omega b980783, omega#333; sovereign-core#277) ---- + +/// Declared serving bounds, the Rust twin of omega's `OmegaGpuServingBounds` +/// (`src/omega_gpu_serving.h`). Every field is a bound the daemon declares at start-up; +/// omega reserves the driver memory for them once and refuses a call past them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ServingBounds { + /// Longest sequence (tokens) one attention call may cover. + pub max_context: u32, + /// Sequences per attention call (the GB10 backend calls attention one sequence at a time: 1). + pub max_seqs: u32, + pub num_q_heads: u32, + pub num_kv_heads: u32, + pub head_dim: u32, + /// Paged KV block size in tokens (power of two). + pub kv_block_size: u32, + /// Most rows one matmul call may carry. + pub max_rows: u32, + /// Widest weight input dimension. + pub max_k: u32, + /// Widest weight output dimension for calls of up to `max_rows` rows. + pub max_n: u32, + /// Widest output dimension for calls of at most 16 rows (the logits projection). + pub max_n_one_row: u32, + /// Matmul kernel cache slots (omega allows at most 32). + pub kernel_slots: u32, +} + +/// Driver bytes a reservation asks for, computed with omega's own formulas +/// (`omega_gpu_attention_reserve`, attention_api.c:664-681; `omega_gpu_matmul_reserve`, +/// matmul_api.c:130-150, at b980783). Reported in the daemon log so a chip run can compare +/// it with the driver's allocation counters. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ServingBytes { + pub attention_pool: u64, + pub attention_q_out: u64, + pub attention_table: u64, + pub matmul_activation: u64, + pub matmul_result: u64, +} + +impl ServingBytes { + pub fn total(&self) -> u64 { + self.attention_pool + + 2 * self.attention_q_out + + self.attention_table + + self.matmul_activation + + self.matmul_result + } +} + +fn round_up(v: u64, to: u64) -> u64 { + v.div_ceil(to) * to +} + +impl ServingBounds { + /// Bytes omega will reserve for these bounds. Tiles: omega `OMEGA_GPU_MATMUL_TILE_M` 16, + /// `_TILE_N` 8, `_TILE_K` 16 (omega_gpu_matmul_api.h:46-48). + pub fn bytes(&self) -> ServingBytes { + let (ctx, seqs) = (self.max_context as u64, self.max_seqs.max(1) as u64); + let (kvh, hd) = (self.num_kv_heads as u64, self.head_dim as u64); + let mut per_seq = 2 * ctx * kvh * hd * 4; + if self.kv_block_size != 0 { + let bs = self.kv_block_size as u64; + per_seq = per_seq.max(round_up(ctx, bs) * kvh * hd * 4); + } + let qo = seqs * self.num_q_heads as u64 * hd * 4; + let table = ((seqs * ctx + seqs) * 4).max(8); + let mp = round_up(self.max_rows as u64, 16); + let kp = round_up(self.max_k as u64, 16); + let mut c = mp * round_up(self.max_n as u64, 8) * 4; + if self.max_n_one_row != 0 { + c = c.max(16 * round_up(self.max_n_one_row as u64, 8) * 4); + } + ServingBytes { + attention_pool: per_seq * seqs, + attention_q_out: qo, + attention_table: table, + matmul_activation: mp * kp * 2, + matmul_result: c, + } + } +} + +/// Reserve the serving buffers once (opens the device if needed). All-or-nothing: if the +/// matmul half is refused the attention half is released again, as omega's own +/// `omega_gpu_reserve_serving` does (`src/omega_gpu_serving.c`, which libomega_gpu.a does not +/// contain at b980783, so the two per-API calls are made here in the same order). +/// On refusal the error carries omega's return-code name and its stage text +/// (for example "serving reservation exceeded" or the driver's allocation failure). Stub: `Unavailable`. +pub fn reserve_serving(b: &ServingBounds) -> Result<(), OmegaGpuError> { + #[cfg(has_omega_gpu)] + { + // SAFETY: plain integer arguments; omega takes its own lock and may open the device. + let rc = unsafe { + ffi::omega_gpu_attention_reserve( + b.max_context, + b.max_seqs.max(1), + b.num_q_heads, + b.num_kv_heads, + b.head_dim, + b.kv_block_size, + ) + }; + if rc != 0 { + return Err(OmegaGpuError::Rc { + rc, + name: attn_rc_name(rc), + }); + } + // SAFETY: as above. + let rc = unsafe { + ffi::omega_gpu_matmul_reserve( + b.max_rows, + b.max_k, + b.max_n, + b.max_n_one_row, + b.kernel_slots, + ) + }; + if rc != 0 { + // SAFETY: no arguments; releases only the attention flag. + unsafe { ffi::omega_gpu_attention_unreserve() }; + return Err(rc_error(rc)); + } + Ok(()) + } + #[cfg(not(has_omega_gpu))] + { + let _ = b; + Err(OmegaGpuError::Unavailable) + } +} + +/// Lift the reservation (buffers stay, growth is allowed again). No-op in the stub. +pub fn release_serving() { + #[cfg(has_omega_gpu)] + // SAFETY: no arguments; omega takes its own lock. + unsafe { + ffi::omega_gpu_attention_unreserve(); + ffi::omega_gpu_matmul_unreserve(); + } +} #[cfg(test)] mod cta_budget_tests { use super::*; diff --git a/omega.lock b/omega.lock index b8b87611..4312c80f 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -01f6a74636b8383b010cdb95597839582c415c27 +b980783a4674275e720592e4c3887679dd24ec8b From f4a3c922f4492cc36378b299bddb067bc2378449 Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 20:24:12 -0500 Subject: [PATCH 2/7] GB10 Qwen3: reserve the serving buffers once at daemon start-up (cut toward #277, not a fix) On the opt-in Qwen3 GB10 path the daemon now calls omega's serving reservation (omega#333) once, after the GPU session is open and before the first request, sized from the declared bounds (context <= min(KV plan, 4096), decode batch 256 / prefill chunk 128 rows, Qwen3 widths, 32 kernel slots). A refusal stops the daemon with a named reason (GB10_SERVING_RESERVATION refused ..., no on-demand fallback). The outcome is logged as a GB10_SERVING_RESERVATION line. The default Qwen3 GB10 refusal is unchanged. CPU tests only. Part of #277. Co-Authored-By: Claude Opus 5.5 --- crates/aien-cli/src/commands.rs | 53 ++++-- crates/aien-inference-abi/src/gb10_serving.rs | 163 +++++++++++++++++- .../aien-inference-abi/src/omega_backend.rs | 2 +- crates/aien-omega-gpu/src/lib.rs | 42 +++++ docs/design/gb10-weight-ownership.md | 8 +- 5 files changed, 241 insertions(+), 27 deletions(-) diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 57fb5f79..28521997 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1525,6 +1525,9 @@ pub async fn run_daemon_server() { // from the loaded model's config and declared context, and the host's // MemAvailable is checked before it is allocated (#239). AIEN_KV_CONTEXT_TOKENS // may lower the context budget below the model's declared context, never raise it. + let model_config = weights.config.clone(); + let (max_batch_rows, prefill_chunk_rows) = + (sched_cfg.max_batch_size, sched_cfg.prefill_chunk_size); let kv_context_cap = match aien_runtime::shared_kv::kv_context_cap_from_env() { Ok(cap) => cap, Err(fatal) => { @@ -1533,22 +1536,21 @@ pub async fn run_daemon_server() { } }; 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, - kv_context_cap, - &aien_runtime::shared_kv::read_mem_available_checked, - aien_runtime::shared_kv::allow_unchecked_memory_from_env(), - ) { - Ok(parts) => parts, - Err(fatal) => { - eprintln!("Fatal: shared KV pool: {}", fatal.red().bold()); - std::process::exit(1); - } - }; + let (spine, backend, kv_plan) = match aien_runtime::shared_kv::build_shared_kv_runtime_for_model( + weights, + tensor_backend, + sched_cfg, + 4096, + kv_context_cap, + &aien_runtime::shared_kv::read_mem_available_checked, + aien_runtime::shared_kv::allow_unchecked_memory_from_env(), + ) { + 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). @@ -1563,6 +1565,25 @@ pub async fn run_daemon_server() { std::process::exit(1); } } + // GB10 Qwen3 (the opt-in path only): reserve the serving buffers once, from the declared + // bounds, before the first request. A refusal stops the daemon by name; there is no + // on-demand fallback (sovereign-core#277, omega#327, omega#333). The outcome is logged + // either way so a chip run can measure it. + match aien_inference_abi::gb10_serving::reserve_gb10_serving( + &model_config, + &aien_inference_abi::gb10_serving::ServingLimits { + context_tokens: kv_plan.context_tokens, + max_batch_rows, + prefill_chunk_rows, + }, + ) { + Ok(Some(reservation)) => println!(" {}", reservation.log_line()), + Ok(None) => {} + Err(fatal) => { + 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/gb10_serving.rs b/crates/aien-inference-abi/src/gb10_serving.rs index bc71ea0a..bc073b1f 100644 --- a/crates/aien-inference-abi/src/gb10_serving.rs +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -1,25 +1,174 @@ -//! STUB (red run): the product path makes no serving reservation call. +//! Start-up reservation of the GB10 serving buffers (sovereign-core#277, a cut toward it). +//! +//! Without it, omega grows the attention staging pool, the matmul activation/result buffers +//! and the matmul kernel cache on demand while serving, and every growth is a driver (RM) +//! allocation that can fail with NV_ERR_NO_MEMORY when MemFree is low (omega#327; omega#332 +//! measured 458 allocations and 456 frees over 428 tokens). omega#333 (b980783) adds an +//! opt-in reservation: allocate once for declared bounds, then serve with zero driver +//! allocations inside them and a named refusal (`TOO_LARGE`) past them. +//! +//! This module derives the bounds from the model and the daemon's declared limits and makes +//! the one call. It applies only on the path that is already opt-in (Qwen3 on the GB10, +//! `AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1`); the default Qwen3 refusal is untouched. It does not +//! claim to fix #277: it is not proven on the chip, and it does not reserve what omega's +//! header lists as not covered (elementwise scratch, the attention kernel cache, the first +//! build of each matmul shape). + +use crate::omega_backend::{gb10_qwen3_opted_in, omega_model_refusal_with, OmegaGb10Backend}; use aien_abi_core::ModelConfig; use aien_omega_gpu::{ServingBounds, ServingBytes}; +/// omega's contiguous f32 attention kernel refuses `seq_len` past this itself +/// (`OMEGA_GPU_ATTN_MAX_GQA_CTX`, omega `src/omega_gpu_attention_api.h:83`), so a larger +/// declared context cannot be served natively and is not reserved. +pub const GB10_ATTENTION_MAX_CONTEXT: u32 = 4096; + +/// Matmul kernel cache depth: 21 distinct (kp, np, grid_x) shapes for Qwen3-4B at the daemon's +/// CTA budget (docs/design/gb10-weight-ownership.md), omega allows at most 32. +pub const GB10_MATMUL_KERNEL_SLOTS: u32 = 32; + +/// What the daemon declares at start-up (aien-cli `run_daemon_server`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ServingLimits { + /// Context the KV pool is planned for (`KvPoolPlan::context_tokens`). pub context_tokens: usize, + /// Most sequences one decode step batches (`SchedulerConfig::max_batch_size`); the batched + /// decode path runs every projection with this many rows. pub max_batch_rows: usize, + /// Prompt tokens per prefill chunk (`SchedulerConfig::prefill_chunk_size`). pub prefill_chunk_rows: usize, } +/// A reservation that was made: the bounds and the driver bytes omega was asked for. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ServingReservation { pub bounds: ServingBounds, pub bytes: ServingBytes, } +impl ServingReservation { + /// The start-up log line a chip run reads. + pub fn log_line(&self) -> String { + let (b, y) = (&self.bounds, &self.bytes); + format!( + "GB10_SERVING_RESERVATION reserved bytes={} (attention pool {} + q/out {}x2 + table {}; matmul activation {} + result {}) \ + bounds: context<={} seqs<={} rows<={} k<={} n<={} logits_n<={} kernel_slots={}; \ + calls past the bounds are refused TOO_LARGE; not covered: elementwise scratch, attention kernel, first build of each matmul shape", + y.total(), + y.attention_pool, + y.attention_q_out, + y.attention_table, + y.matmul_activation, + y.matmul_result, + b.max_context, + b.max_seqs, + b.max_rows, + b.max_k, + b.max_n, + b.max_n_one_row, + b.kernel_slots, + ) + } +} + +fn dim(what: &str, v: usize) -> Result { + match u32::try_from(v) { + Ok(x) if x > 0 => Ok(x), + _ => Err(format!("{what} = {v} is not a usable serving bound")), + } +} + +/// Bounds for `config` under `limits`. Errors name the offending number. +pub fn gb10_serving_bounds( + config: &ModelConfig, + limits: &ServingLimits, +) -> Result { + let q_dim = config.num_heads * config.head_dim; + let kv_dim = config.num_kv_heads * config.head_dim; + // Widest input: o_proj reads q_dim, q/k/v/gate/up read hidden, down_proj reads intermediate. + let max_k = config.hidden_dim.max(q_dim).max(config.intermediate_dim); + // Widest output for a call of up to max_rows rows. The batched decode path projects the + // logits with every decode row (transformer_backend.rs, step 7: matmul_batch M = D), so the + // vocabulary is in the many-row bound as well as the one-row bound. + let max_n = q_dim + .max(kv_dim) + .max(config.hidden_dim) + .max(config.intermediate_dim) + .max(config.vocab_size); + let context = limits + .context_tokens + .min(GB10_ATTENTION_MAX_CONTEXT as usize); + Ok(ServingBounds { + max_context: dim("declared context", context)?, + // omega_backend.rs paged_attention_batch runs one chip_paged_one call per sequence. + max_seqs: 1, + num_q_heads: dim("num_heads", config.num_heads)?, + num_kv_heads: dim("num_kv_heads", config.num_kv_heads)?, + head_dim: dim("head_dim", config.head_dim)?, + kv_block_size: dim("block_size", config.block_size)?, + max_rows: dim( + "max rows (max_batch_size, prefill chunk)", + limits.max_batch_rows.max(limits.prefill_chunk_rows), + )?, + max_k: dim("widest input dimension", max_k)?, + max_n: dim("widest output dimension", max_n)?, + max_n_one_row: dim("vocab_size", config.vocab_size)?, + kernel_slots: GB10_MATMUL_KERNEL_SLOTS, + }) +} + +/// [`reserve_gb10_serving`] with the GPU, the opt-in and the reservation call passed in. +/// +/// `Ok(None)`: the reservation does not apply (not a GB10 build, not Qwen3, or the Qwen3 opt-in +/// is off, in which case the default refusal in `check_model` stops the model before any +/// serving). `Ok(Some(_))`: reserved. `Err(_)`: omega refused the reservation (or a bound could +/// not be formed); the caller must refuse to serve. There is no on-demand fallback. pub fn reserve_gb10_serving_with( - _config: &ModelConfig, - _limits: &ServingLimits, - _gpu_native: bool, - _qwen3_opted_in: bool, - _reserve: &dyn Fn(&ServingBounds) -> Result<(), String>, + config: &ModelConfig, + limits: &ServingLimits, + gpu_native: bool, + qwen3_opted_in: bool, + reserve: &dyn Fn(&ServingBounds) -> Result<(), String>, +) -> Result, String> { + if !gpu_native || !config.qk_norm || omega_model_refusal_with(config, qwen3_opted_in).is_some() + { + return Ok(None); + } + let refuse = |why: String| { + format!( + "GB10_SERVING_RESERVATION refused for {:?}: {why}; refusing to serve (sovereign-core#277: \ + no on-demand fallback, because on-demand growth is the driver allocation that fails when MemFree is low)", + config.model_id + ) + }; + let bounds = gb10_serving_bounds(config, limits).map_err(&refuse)?; + reserve(&bounds).map_err(&refuse)?; + Ok(Some(ServingReservation { + bounds, + bytes: bounds.bytes(), + })) +} + +/// Reserve the serving buffers once, after the GPU session and the weights are set up and +/// before the first request. See [`reserve_gb10_serving_with`] for the outcomes. +pub fn reserve_gb10_serving( + config: &ModelConfig, + limits: &ServingLimits, ) -> Result, String> { - Ok(None) + reserve_gb10_serving_with( + config, + limits, + OmegaGb10Backend::new().is_available(), + gb10_qwen3_opted_in(), + &|b| { + aien_omega_gpu::reserve_serving(b).map_err(|e| { + let stage = aien_omega_gpu::last_error(); + if stage.is_empty() { + e.to_string() + } else { + format!("{e} (omega: {stage})") + } + }) + }, + ) } diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 12c97a99..ea1c9137 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -534,7 +534,7 @@ pub fn omega_model_refusal(config: &ModelConfig) -> Option { /// open. Only the exact value `1` opts in; unset or anything else keeps the refusal. pub const GB10_QWEN3_OPT_IN_ENV: &str = "AIEN_GB10_QWEN3_DECLARED_ATTEMPT"; -fn gb10_qwen3_opted_in() -> bool { +pub(crate) fn gb10_qwen3_opted_in() -> bool { std::env::var(GB10_QWEN3_OPT_IN_ENV).is_ok_and(|v| v == "1") } diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 9963da68..46aa9c2f 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -1157,6 +1157,48 @@ mod spin_us_tests { } } + fn qwen3_4b_bounds() -> ServingBounds { + ServingBounds { + max_context: 4096, + max_seqs: 1, + num_q_heads: 32, + num_kv_heads: 8, + head_dim: 128, + kv_block_size: 16, + max_rows: 256, + max_k: 9728, + max_n: 151936, + max_n_one_row: 151936, + kernel_slots: 32, + } + } + + #[test] + fn serving_bytes_follow_omegas_formulas() { + // omega attention_api.c:664-681 and matmul_api.c:130-150 at b980783, Qwen3-4B shape. + let y = qwen3_4b_bounds().bytes(); + assert_eq!(y.attention_pool, 2 * 4096 * 8 * 128 * 4); // 32 MiB + assert_eq!(y.attention_q_out, 32 * 128 * 4); + assert_eq!(y.attention_table, (4096 + 1) * 4); + assert_eq!(y.matmul_activation, 256 * 9728 * 2); + assert_eq!(y.matmul_result, 256 * 151936 * 4); + // under half a block of context the paged path stages a whole block, the larger one + let mut b = qwen3_4b_bounds(); + (b.max_context, b.kv_block_size) = (16, 64); + assert_eq!(b.bytes().attention_pool, 64 * 8 * 128 * 4); + } + + #[test] + fn reserving_without_the_engine_is_unavailable() { + if !is_native() { + assert_eq!( + reserve_serving(&qwen3_4b_bounds()), + Err(OmegaGpuError::Unavailable) + ); + release_serving(); + } + } + #[test] fn reading_the_window_matches_the_build() { if is_native() { diff --git a/docs/design/gb10-weight-ownership.md b/docs/design/gb10-weight-ownership.md index 6dfc6057..e8065a6b 100644 --- a/docs/design/gb10-weight-ownership.md +++ b/docs/design/gb10-weight-ownership.md @@ -44,9 +44,11 @@ layers, 32 query heads, 8 KV heads, head_dim 128, vocab 151936, tied embeddings, counts 0 allocations and 0 frees after warm-up; a request past the reservation is refused with a named error before any driver call. Not covered: elementwise scratch, the attention kernel cache (8 slots), prebuilding matmul shapes at reserve time. -- Not done: sovereign-core does not call the reservation yet (its `omega.lock` is still 01f6a74, - before #333), so the daemon's behaviour is unchanged. Wiring it in is a separate reviewed change - with its own chip attempt under the #277 protocol. Cuts A and C are not started. The default +- Wired in (draft PR "Part of #277", not yet proven on the chip): `omega.lock` is b980783 and the + daemon, on the opt-in Qwen3 GB10 path only, calls the reservation once after the session opens and + before the first request (`aien-inference-abi/src/gb10_serving.rs`), logging a + `GB10_SERVING_RESERVATION` line and refusing to serve by name if omega refuses. Its chip attempt + under the #277 protocol is still to be declared and run. Cuts A and C are not started. The default refusal of Qwen3 on the GB10 stays. - The #277 chip attempts so far: attempt 1 (06:33Z) and attempt 2 (21:45Z) are both INVALID CONDITION: the baseline did not reproduce the failure, so the fix runs were skipped by the rule fixed in advance. From 14943f5dc86b5ff098effba43635086643e21a0f Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 20:30:38 -0500 Subject: [PATCH 3/7] Use omega's omega_gpu_reserve_serving (omega#338); test the daemon's start-up decision Drops the Rust reserve+rollback duplicate: binds omega_gpu_reserve_serving / omega_gpu_serving_release and OmegaGpuServingBounds. omega.lock pinned to omega c1/lib-serving 235564d (omega#338); re-pin to the merge commit once it merges. The daemon decision is a pure function (daemon_serving_reservation) with CPU tests: one call from the KV plan, named refusal, no call on the default path. Reserved-byte sizing checked against omega's fake driver layer (194170880 bytes). Part of #277. Co-Authored-By: Claude Opus 5.5 --- crates/aien-cli/src/commands.rs | 157 +++++++++++++++++- crates/aien-inference-abi/src/gb10_serving.rs | 35 ++-- crates/aien-omega-gpu/src/ffi.rs | 43 ++--- crates/aien-omega-gpu/src/lib.rs | 84 +++++----- omega.lock | 2 +- 5 files changed, 221 insertions(+), 100 deletions(-) diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 28521997..c59d5a0a 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1490,6 +1490,34 @@ fn apply_omega_cta_budget(budget: Option) -> Result Result<(), String>, +) -> Result, String> { + let limits = aien_inference_abi::gb10_serving::ServingLimits { + context_tokens: kv_context_tokens, + max_batch_rows: sched.max_batch_size, + prefill_chunk_rows: sched.prefill_chunk_size, + }; + aien_inference_abi::gb10_serving::reserve_gb10_serving_with( + model_config, + &limits, + gpu_native, + qwen3_opted_in, + reserve, + ) + .map(|r| r.map(|r| r.log_line())) +} + pub async fn run_daemon_server() { println!( "{}", @@ -1526,8 +1554,7 @@ pub async fn run_daemon_server() { // MemAvailable is checked before it is allocated (#239). AIEN_KV_CONTEXT_TOKENS // may lower the context budget below the model's declared context, never raise it. let model_config = weights.config.clone(); - let (max_batch_rows, prefill_chunk_rows) = - (sched_cfg.max_batch_size, sched_cfg.prefill_chunk_size); + let sched_for_reservation = sched_cfg.clone(); let kv_context_cap = match aien_runtime::shared_kv::kv_context_cap_from_env() { Ok(cap) => cap, Err(fatal) => { @@ -1569,15 +1596,15 @@ pub async fn run_daemon_server() { // bounds, before the first request. A refusal stops the daemon by name; there is no // on-demand fallback (sovereign-core#277, omega#327, omega#333). The outcome is logged // either way so a chip run can measure it. - match aien_inference_abi::gb10_serving::reserve_gb10_serving( + match daemon_serving_reservation( &model_config, - &aien_inference_abi::gb10_serving::ServingLimits { - context_tokens: kv_plan.context_tokens, - max_batch_rows, - prefill_chunk_rows, - }, + kv_plan.context_tokens, + &sched_for_reservation, + gpu_native, + std::env::var(aien_inference_abi::GB10_QWEN3_OPT_IN_ENV).is_ok_and(|v| v == "1"), + &aien_inference_abi::gb10_serving::omega_reserve, ) { - Ok(Some(reservation)) => println!(" {}", reservation.log_line()), + Ok(Some(line)) => println!(" {line}"), Ok(None) => {} Err(fatal) => { eprintln!("Fatal: {}", fatal.red().bold()); @@ -1985,6 +2012,118 @@ pub async fn handle_aegis_command() { mod tests { use super::*; + // ---- GB10 serving reservation: the daemon's start-up decision (sovereign-core#277) ---- + + fn qwen3_4b_config() -> aien_inference_abi::ModelConfig { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config"); + let cfg = std::fs::read_to_string(dir.join("config.json")).unwrap(); + let gen = std::fs::read_to_string(dir.join("generation_config.json")).unwrap(); + aien_inference_abi::model_config_from_hf_json( + "Qwen/Qwen3-4B-Instruct-2507", + &cfg, + Some(&gen), + ) + .unwrap() + } + + /// The scheduler limits `run_daemon_server` declares. + fn daemon_sched() -> aien_scheduler::SchedulerConfig { + aien_scheduler::SchedulerConfig { + max_batch_size: 256, + max_batch_tokens: 16384, + max_prefill_tokens: 8192, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 64, + } + } + + #[test] + fn opt_in_qwen3_gb10_reserves_exactly_once_from_the_kv_plan() { + let cfg = qwen3_4b_config(); + // the plan the daemon builds (context capped like AIEN_KV_CONTEXT_TOKENS=2048) + let plan = aien_runtime::shared_kv::plan_checked_model_kv( + &cfg, + Some(2048), + &|| Ok(u64::MAX), + false, + ) + .unwrap(); + let calls = std::cell::RefCell::new(Vec::new()); + let line = daemon_serving_reservation( + &cfg, + plan.context_tokens, + &daemon_sched(), + true, + true, + &|b| { + calls.borrow_mut().push(*b); + Ok(()) + }, + ) + .unwrap() + .expect("reserved on the opt-in path"); + let calls = calls.into_inner(); + assert_eq!(calls.len(), 1, "exactly one reservation call"); + assert_eq!(calls[0].max_context, 2048, "from the KV plan"); + assert_eq!(calls[0].max_rows, 256, "from the scheduler"); + assert_eq!(calls[0].kv_block_size as usize, plan.block_size); + assert!( + line.starts_with("GB10_SERVING_RESERVATION reserved bytes="), + "{line}" + ); + } + + #[test] + fn a_refused_reservation_stops_the_daemon_by_name() { + let err = daemon_serving_reservation( + &qwen3_4b_config(), + 4096, + &daemon_sched(), + true, + true, + &|_| Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string()), + ) + .unwrap_err(); + assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}"); + assert!( + err.contains("CHIP_FAIL") && err.contains("no on-demand fallback"), + "{err}" + ); + } + + #[test] + fn default_path_makes_no_reservation_call() { + let never = |_: &aien_omega_gpu::ServingBounds| -> Result<(), String> { + panic!("the default path must not reserve") + }; + // Qwen3 without the declared-attempt opt-in (the default refusal path) + assert_eq!( + daemon_serving_reservation( + &qwen3_4b_config(), + 4096, + &daemon_sched(), + true, + false, + &never + ), + Ok(None) + ); + // CPU daemon (no GB10 engine linked) + assert_eq!( + daemon_serving_reservation( + &qwen3_4b_config(), + 4096, + &daemon_sched(), + false, + true, + &never + ), + Ok(None) + ); + } + #[test] fn model_identity_needs_real_weights_and_a_parsed_tokenizer() { let loaded = DaemonModelManifest { diff --git a/crates/aien-inference-abi/src/gb10_serving.rs b/crates/aien-inference-abi/src/gb10_serving.rs index bc073b1f..18beae5d 100644 --- a/crates/aien-inference-abi/src/gb10_serving.rs +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -14,7 +14,7 @@ //! header lists as not covered (elementwise scratch, the attention kernel cache, the first //! build of each matmul shape). -use crate::omega_backend::{gb10_qwen3_opted_in, omega_model_refusal_with, OmegaGb10Backend}; +use crate::omega_backend::omega_model_refusal_with; use aien_abi_core::ModelConfig; use aien_omega_gpu::{ServingBounds, ServingBytes}; @@ -149,26 +149,15 @@ pub fn reserve_gb10_serving_with( })) } -/// Reserve the serving buffers once, after the GPU session and the weights are set up and -/// before the first request. See [`reserve_gb10_serving_with`] for the outcomes. -pub fn reserve_gb10_serving( - config: &ModelConfig, - limits: &ServingLimits, -) -> Result, String> { - reserve_gb10_serving_with( - config, - limits, - OmegaGb10Backend::new().is_available(), - gb10_qwen3_opted_in(), - &|b| { - aien_omega_gpu::reserve_serving(b).map_err(|e| { - let stage = aien_omega_gpu::last_error(); - if stage.is_empty() { - e.to_string() - } else { - format!("{e} (omega: {stage})") - } - }) - }, - ) +/// The real reservation call: omega's `omega_gpu_reserve_serving`, with omega's stage text added to +/// a refusal. The daemon passes this to [`reserve_gb10_serving_with`]. +pub fn omega_reserve(b: &ServingBounds) -> Result<(), String> { + aien_omega_gpu::reserve_serving(b).map_err(|e| { + let stage = aien_omega_gpu::last_error(); + if stage.is_empty() { + e.to_string() + } else { + format!("{e} (omega: {stage})") + } + }) } diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index 2510cf92..a30e1efb 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -81,6 +81,23 @@ impl OmegaGpuMatmulInfo { pub struct OmegaGpuTensor { _private: [u8; 0], } +#[cfg(has_omega_gpu)] +/// omega `OmegaGpuServingBounds` (`src/omega_gpu_serving.h`), field for field. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct OmegaGpuServingBounds { + pub max_context: u32, + pub max_seqs: u32, + pub num_q_heads: u32, + pub num_kv_heads: u32, + pub head_dim: u32, + pub kv_block_size: u32, + pub max_rows: u32, + pub max_k: u32, + pub max_n: u32, + pub max_n_one_row: u32, + pub kernel_slots: u32, +} #[cfg(has_omega_gpu)] extern "C" { @@ -144,17 +161,11 @@ extern "C" { // -1 above OMEGA_GPU_SESSION_MAX_SPIN_US with the setting unchanged (omega#328). pub fn omega_gpu_session_set_spin_us(us: u32) -> c_int; pub fn omega_gpu_session_spin_us() -> u32; - // omega b980783 `src/omega_gpu_matmul_api.h` (opt-in serving reservation, omega#333): activation and - // result staging for calls of up to max_rows rows plus a deeper kernel cache. 0 on success, else an - // OMEGA_GPU_MATMUL_* code (omega_gpu_matmul_last_error() has the text). - pub fn omega_gpu_matmul_reserve( - max_rows: u32, - max_k: u32, - max_n: u32, - max_n_one_row: u32, - kernel_slots: u32, - ) -> c_int; - pub fn omega_gpu_matmul_unreserve(); + // omega c1/lib-serving `src/omega_gpu_serving.h` (omega#333 reservation, shipped in libomega_gpu.a by + // omega#338): one all-or-nothing call; 0 on success, else the first failing OMEGA_GPU_MATMUL_* / + // OMEGA_GPU_ATTN_* code (omega_gpu_matmul_last_error() has the text). + pub fn omega_gpu_reserve_serving(b: *const OmegaGpuServingBounds) -> c_int; + pub fn omega_gpu_serving_release(); } // ---- omega `src/omega_gpu_elementwise_api.h` (FB-1 cut 4, pinned 2636409) ---- @@ -371,14 +382,4 @@ extern "C" { ) -> c_int; pub fn omega_gpu_attention_rc_name(rc: c_int) -> *const c_char; pub fn omega_gpu_attention_last_error() -> *const c_char; - // omega b980783 `src/omega_gpu_attention_api.h` (opt-in serving reservation, omega#333). - pub fn omega_gpu_attention_reserve( - max_context: u32, - max_seqs: u32, - num_q_heads: u32, - num_kv_heads: u32, - head_dim: u32, - kv_block_size: u32, - ) -> c_int; - pub fn omega_gpu_attention_unreserve(); } diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 46aa9c2f..f0af5bc9 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -942,6 +942,8 @@ impl ServingBounds { /// Bytes omega will reserve for these bounds. Tiles: omega `OMEGA_GPU_MATMUL_TILE_M` 16, /// `_TILE_N` 8, `_TILE_K` 16 (omega_gpu_matmul_api.h:46-48). pub fn bytes(&self) -> ServingBytes { + // Each buffer is rounded to a 4 KiB page by omega (checked against omega's fake driver + // layer: 194170880 bytes for the Qwen3-4B daemon bounds, see the unit test). let (ctx, seqs) = (self.max_context as u64, self.max_seqs.max(1) as u64); let (kvh, hd) = (self.num_kv_heads as u64, self.head_dim as u64); let mut per_seq = 2 * ctx * kvh * hd * 4; @@ -950,7 +952,7 @@ impl ServingBounds { per_seq = per_seq.max(round_up(ctx, bs) * kvh * hd * 4); } let qo = seqs * self.num_q_heads as u64 * hd * 4; - let table = ((seqs * ctx + seqs) * 4).max(8); + let table = round_up(((seqs * ctx + seqs) * 4).max(8), 4096); let mp = round_up(self.max_rows as u64, 16); let kp = round_up(self.max_k as u64, 16); let mut c = mp * round_up(self.max_n as u64, 8) * 4; @@ -958,57 +960,44 @@ impl ServingBounds { c = c.max(16 * round_up(self.max_n_one_row as u64, 8) * 4); } ServingBytes { - attention_pool: per_seq * seqs, - attention_q_out: qo, + attention_pool: round_up(per_seq * seqs, 4096), + attention_q_out: round_up(qo, 4096), attention_table: table, - matmul_activation: mp * kp * 2, - matmul_result: c, + matmul_activation: round_up(mp * kp * 2, 4096), + matmul_result: round_up(c, 4096), } } } -/// Reserve the serving buffers once (opens the device if needed). All-or-nothing: if the -/// matmul half is refused the attention half is released again, as omega's own -/// `omega_gpu_reserve_serving` does (`src/omega_gpu_serving.c`, which libomega_gpu.a does not -/// contain at b980783, so the two per-API calls are made here in the same order). -/// On refusal the error carries omega's return-code name and its stage text -/// (for example "serving reservation exceeded" or the driver's allocation failure). Stub: `Unavailable`. +/// Reserve the serving buffers once (opens the device if needed): omega's own all-or-nothing +/// `omega_gpu_reserve_serving` (`src/omega_gpu_serving.c`, in libomega_gpu.a since omega#338). +/// On refusal the error carries omega's return-code name; callers add `last_error()` for the +/// stage text (for example "serving reservation exceeded" or the driver's allocation failure). +/// Stub: `Unavailable`. pub fn reserve_serving(b: &ServingBounds) -> Result<(), OmegaGpuError> { #[cfg(has_omega_gpu)] { - // SAFETY: plain integer arguments; omega takes its own lock and may open the device. - let rc = unsafe { - ffi::omega_gpu_attention_reserve( - b.max_context, - b.max_seqs.max(1), - b.num_q_heads, - b.num_kv_heads, - b.head_dim, - b.kv_block_size, - ) - }; - if rc != 0 { - return Err(OmegaGpuError::Rc { - rc, - name: attn_rc_name(rc), - }); - } - // SAFETY: as above. - let rc = unsafe { - ffi::omega_gpu_matmul_reserve( - b.max_rows, - b.max_k, - b.max_n, - b.max_n_one_row, - b.kernel_slots, - ) + let c = ffi::OmegaGpuServingBounds { + max_context: b.max_context, + max_seqs: b.max_seqs, + num_q_heads: b.num_q_heads, + num_kv_heads: b.num_kv_heads, + head_dim: b.head_dim, + kv_block_size: b.kv_block_size, + max_rows: b.max_rows, + max_k: b.max_k, + max_n: b.max_n, + max_n_one_row: b.max_n_one_row, + kernel_slots: b.kernel_slots, }; - if rc != 0 { - // SAFETY: no arguments; releases only the attention flag. - unsafe { ffi::omega_gpu_attention_unreserve() }; - return Err(rc_error(rc)); + // SAFETY: `c` is a valid, fully initialised repr(C) struct that omega only reads. + let rc = unsafe { ffi::omega_gpu_reserve_serving(&c) }; + if rc == 0 { + Ok(()) + } else { + // matmul and attention codes share the numbering 0/-1..-5; the matmul table names them. + Err(rc_error(rc)) } - Ok(()) } #[cfg(not(has_omega_gpu))] { @@ -1022,10 +1011,10 @@ pub fn release_serving() { #[cfg(has_omega_gpu)] // SAFETY: no arguments; omega takes its own lock. unsafe { - ffi::omega_gpu_attention_unreserve(); - ffi::omega_gpu_matmul_unreserve(); + ffi::omega_gpu_serving_release(); } } + #[cfg(test)] mod cta_budget_tests { use super::*; @@ -1178,8 +1167,11 @@ mod spin_us_tests { // omega attention_api.c:664-681 and matmul_api.c:130-150 at b980783, Qwen3-4B shape. let y = qwen3_4b_bounds().bytes(); assert_eq!(y.attention_pool, 2 * 4096 * 8 * 128 * 4); // 32 MiB - assert_eq!(y.attention_q_out, 32 * 128 * 4); - assert_eq!(y.attention_table, (4096 + 1) * 4); + assert_eq!(y.attention_q_out, 16384); + assert_eq!(y.attention_table, 20480); // (4096 + 1) * 4 rounded up to a page + // Measured, not derived: omega_gpu_reserve_serving on its fake driver layer with these + // bounds asked the driver for exactly 194170880 bytes (6 buffers). + assert_eq!(y.total(), 194_170_880); assert_eq!(y.matmul_activation, 256 * 9728 * 2); assert_eq!(y.matmul_result, 256 * 151936 * 4); // under half a block of context the paged path stages a whole block, the larger one diff --git a/omega.lock b/omega.lock index 4312c80f..8ef18135 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -b980783a4674275e720592e4c3887679dd24ec8b +235564d5060857e46f2e7b4c25c673d0054afb14 From a7778c32efc1d937f2de51a21a5bb42bfbc5c8d6 Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 21:24:42 -0500 Subject: [PATCH 4/7] Log GB10 allocation counters after warm-up and per request; pin omega 3b11eb0 Part of #277. Binds omega_gpu_session_alloc_stats; the daemon prints GB10_SERVING_ALLOC after warm-up and the change since then after every request, with a visible NONZERO flag. Order stays reserve, prepare, seal. Co-Authored-By: Claude Sonnet 5.5 --- crates/aien-cli/src/commands.rs | 286 ++++++++++++------ crates/aien-inference-abi/src/gb10_serving.rs | 203 ++++++++++--- .../tests/gb10_serving_reservation.rs | 182 ++++++++--- crates/aien-omega-gpu/src/ffi.rs | 17 +- crates/aien-omega-gpu/src/lib.rs | 50 ++- crates/aien-runtime/src/server.rs | 20 ++ omega.lock | 2 +- 7 files changed, 579 insertions(+), 181 deletions(-) diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index c59d5a0a..ce0f9385 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1490,10 +1490,23 @@ fn apply_omega_cta_budget(budget: Option) -> Result aien_scheduler::SchedulerConfig { + aien_scheduler::SchedulerConfig { + max_batch_size: 256, + max_batch_tokens: 16384, + max_prefill_tokens: 8192, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 64, + } +} + /// The daemon's start-up decision for the GB10 serving reservation, apart from the chip so a CPU /// test can run it: derives the bounds from the KV plan's context and the scheduler limits, makes -/// the one reservation call through `reserve` on the opt-in Qwen3 GB10 path (and never elsewhere), -/// and returns the log line, or the named refusal that stops the daemon (no on-demand fallback). +/// runs reserve, prepare of every (rows, weight shape) kernel, then seal through `ops` on the opt-in +/// Qwen3 GB10 path (and never elsewhere), and returns the log line, or the named refusal that stops the daemon (no on-demand fallback). /// `run_daemon_server` calls it once, before the server is built, hence before any request. fn daemon_serving_reservation( model_config: &aien_inference_abi::ModelConfig, @@ -1501,7 +1514,7 @@ fn daemon_serving_reservation( sched: &aien_scheduler::SchedulerConfig, gpu_native: bool, qwen3_opted_in: bool, - reserve: &dyn Fn(&aien_omega_gpu::ServingBounds) -> Result<(), String>, + ops: &dyn aien_inference_abi::gb10_serving::ServingOps, ) -> Result, String> { let limits = aien_inference_abi::gb10_serving::ServingLimits { context_tokens: kv_context_tokens, @@ -1513,7 +1526,7 @@ fn daemon_serving_reservation( &limits, gpu_native, qwen3_opted_in, - reserve, + ops, ) .map(|r| r.map(|r| r.log_line())) } @@ -1530,14 +1543,7 @@ pub async fn run_daemon_server() { std::process::exit(1); } let socket_path = aien_runtime::client::AienRuntimeClient::default_socket_path(); - let sched_cfg = aien_scheduler::SchedulerConfig { - max_batch_size: 256, - max_batch_tokens: 16384, - max_prefill_tokens: 8192, - prefill_chunk_size: 128, - chunk_prefill: true, - watermark_blocks: 64, - }; + let sched_cfg = daemon_scheduler_config(); let (weights, tensor_backend, backend_label, model_label, tokenizer, identity) = match build_native_daemon_backend() { @@ -1563,21 +1569,22 @@ pub async fn run_daemon_server() { } }; 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, - kv_context_cap, - &aien_runtime::shared_kv::read_mem_available_checked, - aien_runtime::shared_kv::allow_unchecked_memory_from_env(), - ) { - Ok(parts) => parts, - Err(fatal) => { - eprintln!("Fatal: shared KV pool: {}", fatal.red().bold()); - std::process::exit(1); - } - }; + let (spine, backend, _kv_plan) = + match aien_runtime::shared_kv::build_shared_kv_runtime_for_model( + weights, + tensor_backend, + sched_cfg, + 4096, + kv_context_cap, + &aien_runtime::shared_kv::read_mem_available_checked, + aien_runtime::shared_kv::allow_unchecked_memory_from_env(), + ) { + 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). @@ -1596,15 +1603,23 @@ pub async fn run_daemon_server() { // bounds, before the first request. A refusal stops the daemon by name; there is no // on-demand fallback (sovereign-core#277, omega#327, omega#333). The outcome is logged // either way so a chip run can measure it. + let mut serving_probe: Option< + std::sync::Arc, + > = None; match daemon_serving_reservation( &model_config, - kv_plan.context_tokens, + _kv_plan.context_tokens, &sched_for_reservation, gpu_native, std::env::var(aien_inference_abi::GB10_QWEN3_OPT_IN_ENV).is_ok_and(|v| v == "1"), - &aien_inference_abi::gb10_serving::omega_reserve, + &aien_inference_abi::gb10_serving::OmegaServingOps, ) { - Ok(Some(line)) => println!(" {line}"), + Ok(Some(line)) => { + println!(" {line}"); + serving_probe = Some(std::sync::Arc::new( + aien_inference_abi::gb10_serving::AllocProbe::omega(), + )); + } Ok(None) => {} Err(fatal) => { eprintln!("Fatal: {}", fatal.red().bold()); @@ -1612,6 +1627,9 @@ pub async fn run_daemon_server() { } } let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path); + if let Some(probe) = serving_probe { + server.set_serving_probe(probe); + } println!(" Backend: {}", backend_label.green()); println!(" Model: {}", model_label.yellow()); @@ -2027,20 +2045,73 @@ mod tests { .unwrap() } - /// The scheduler limits `run_daemon_server` declares. - fn daemon_sched() -> aien_scheduler::SchedulerConfig { - aien_scheduler::SchedulerConfig { - max_batch_size: 256, - max_batch_tokens: 16384, - max_prefill_tokens: 8192, - prefill_chunk_size: 128, - chunk_prefill: true, - watermark_blocks: 64, + use aien_inference_abi::gb10_serving::ServingOps; + use std::cell::RefCell; + + #[derive(Debug, Clone, PartialEq, Eq)] + enum Ev { + Reserve(aien_omega_gpu::ServingBounds), + Prepare(u32, u32, u32), + Seal, + } + + /// Records every omega call in order; `fail_prepare_at` makes that (0-based) prepare fail. + struct Recorder { + events: RefCell>, + fail_prepare_at: Option, + refuse_reserve: bool, + } + + impl Recorder { + fn new() -> Self { + Recorder { + events: RefCell::new(Vec::new()), + fail_prepare_at: None, + refuse_reserve: false, + } + } + } + + impl ServingOps for Recorder { + fn reserve(&self, b: &aien_omega_gpu::ServingBounds) -> Result<(), String> { + self.events.borrow_mut().push(Ev::Reserve(*b)); + if self.refuse_reserve { + return Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string()); + } + Ok(()) + } + fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String> { + let mut ev = self.events.borrow_mut(); + let nth = ev.iter().filter(|e| matches!(e, Ev::Prepare(..))).count(); + ev.push(Ev::Prepare(m, k, n)); + if self.fail_prepare_at == Some(nth) { + return Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string()); + } + Ok(()) + } + fn seal(&self) { + self.events.borrow_mut().push(Ev::Seal); } } + fn run( + rec: &Recorder, + ctx: usize, + native: bool, + opted_in: bool, + ) -> Result, String> { + daemon_serving_reservation( + &qwen3_4b_config(), + ctx, + &daemon_scheduler_config(), + native, + opted_in, + rec, + ) + } + #[test] - fn opt_in_qwen3_gb10_reserves_exactly_once_from_the_kv_plan() { + fn opt_in_qwen3_gb10_reserves_prepares_every_shape_and_seals_in_order() { let cfg = qwen3_4b_config(); // the plan the daemon builds (context capped like AIEN_KV_CONTEXT_TOKENS=2048) let plan = aien_runtime::shared_kv::plan_checked_model_kv( @@ -2050,25 +2121,52 @@ mod tests { false, ) .unwrap(); - let calls = std::cell::RefCell::new(Vec::new()); - let line = daemon_serving_reservation( - &cfg, - plan.context_tokens, - &daemon_sched(), - true, - true, - &|b| { - calls.borrow_mut().push(*b); - Ok(()) - }, - ) - .unwrap() - .expect("reserved on the opt-in path"); - let calls = calls.into_inner(); - assert_eq!(calls.len(), 1, "exactly one reservation call"); - assert_eq!(calls[0].max_context, 2048, "from the KV plan"); - assert_eq!(calls[0].max_rows, 256, "from the scheduler"); - assert_eq!(calls[0].kv_block_size as usize, plan.block_size); + let rec = Recorder::new(); + let line = run(&rec, plan.context_tokens, true, true) + .unwrap() + .expect("reserved on the opt-in path"); + let ev = rec.events.borrow(); + // exactly one reserve, first, with bounds from the KV plan and the scheduler + let Ev::Reserve(b) = &ev[0] else { + panic!("the first omega call must be the reservation: {:?}", ev[0]) + }; + assert_eq!(ev.iter().filter(|e| matches!(e, Ev::Reserve(_))).count(), 1); + assert_eq!(b.max_context, 2048, "from the KV plan"); + assert_eq!(b.max_rows, 256, "from the scheduler"); + assert_eq!(b.kernel_slots, 128); + // every (rows 1..=256) x (shape from the model config) is prepared, each exactly once + let shapes = aien_inference_abi::gb10_serving::serving_matmul_shapes(&cfg).unwrap(); + assert_eq!(shapes.len(), 6, "q, kv, o, gate/up, down, logits"); + assert!( + shapes.contains(&(2560, cfg.vocab_size as u32)), + "logits included" + ); + let prepared: Vec<_> = ev + .iter() + .filter_map(|e| match e { + Ev::Prepare(m, k, n) => Some((*m, *k, *n)), + _ => None, + }) + .collect(); + let want: std::collections::BTreeSet<_> = (1..=256u32) + .flat_map(|m| shapes.iter().map(move |&(k, n)| (m, k, n))) + .collect(); + assert_eq!(prepared.len(), 256 * 6); + assert_eq!( + prepared + .iter() + .copied() + .collect::>(), + want + ); + // seal is last: after all prepares, before serving can start + assert_eq!(ev.last(), Some(&Ev::Seal)); + assert_eq!(ev.iter().filter(|e| **e == Ev::Seal).count(), 1); + assert_eq!(ev.len(), 1 + 256 * 6 + 1); + assert!( + line.contains("prepared 1536 matmul kernel calls in"), + "{line}" + ); assert!( line.starts_with("GB10_SERVING_RESERVATION reserved bytes="), "{line}" @@ -2076,52 +2174,52 @@ mod tests { } #[test] - fn a_refused_reservation_stops_the_daemon_by_name() { - let err = daemon_serving_reservation( - &qwen3_4b_config(), - 4096, - &daemon_sched(), - true, - true, - &|_| Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string()), - ) - .unwrap_err(); + fn a_refused_reservation_stops_the_daemon_by_name_before_any_prepare() { + let mut rec = Recorder::new(); + rec.refuse_reserve = true; + let err = run(&rec, 4096, true, true).unwrap_err(); assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}"); assert!( err.contains("CHIP_FAIL") && err.contains("no on-demand fallback"), "{err}" ); + assert_eq!( + rec.events.borrow().len(), + 1, + "nothing after a refused reserve" + ); } #[test] - fn default_path_makes_no_reservation_call() { - let never = |_: &aien_omega_gpu::ServingBounds| -> Result<(), String> { - panic!("the default path must not reserve") - }; - // Qwen3 without the declared-attempt opt-in (the default refusal path) + fn a_prepare_failure_is_the_same_named_refusal_and_never_seals() { + let mut rec = Recorder::new(); + rec.fail_prepare_at = Some(7); + let err = run(&rec, 4096, true, true).unwrap_err(); + assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}"); + assert!(err.contains("matmul kernel prepare m="), "{err}"); + let ev = rec.events.borrow(); assert_eq!( - daemon_serving_reservation( - &qwen3_4b_config(), - 4096, - &daemon_sched(), - true, - false, - &never - ), - Ok(None) + ev.len(), + 1 + 8, + "reserve + 8 prepares, the 8th failed, stop" ); + assert!(!ev.contains(&Ev::Seal), "a failed start-up must not seal"); + } + + #[test] + fn default_path_makes_no_omega_call() { + // Qwen3 without the declared-attempt opt-in (the default refusal path) + let rec = Recorder::new(); + assert_eq!(run(&rec, 4096, true, false), Ok(None)); // CPU daemon (no GB10 engine linked) - assert_eq!( - daemon_serving_reservation( - &qwen3_4b_config(), - 4096, - &daemon_sched(), - false, - true, - &never - ), - Ok(None) - ); + assert_eq!(run(&rec, 4096, false, true), Ok(None)); + assert!(rec.events.borrow().is_empty()); + } + + #[test] + fn the_shared_scheduler_config_is_the_daemons() { + let s = daemon_scheduler_config(); + assert_eq!((s.max_batch_size, s.prefill_chunk_size), (256, 128)); } #[test] diff --git a/crates/aien-inference-abi/src/gb10_serving.rs b/crates/aien-inference-abi/src/gb10_serving.rs index 18beae5d..3c04ff5c 100644 --- a/crates/aien-inference-abi/src/gb10_serving.rs +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -1,31 +1,39 @@ -//! Start-up reservation of the GB10 serving buffers (sovereign-core#277, a cut toward it). +//! Start-up reservation of the GB10 serving buffers and kernels (sovereign-core#277, a cut +//! toward it). //! //! Without it, omega grows the attention staging pool, the matmul activation/result buffers //! and the matmul kernel cache on demand while serving, and every growth is a driver (RM) //! allocation that can fail with NV_ERR_NO_MEMORY when MemFree is low (omega#327; omega#332 -//! measured 458 allocations and 456 frees over 428 tokens). omega#333 (b980783) adds an -//! opt-in reservation: allocate once for declared bounds, then serve with zero driver -//! allocations inside them and a named refusal (`TOO_LARGE`) past them. +//! measured 458 allocations and 456 frees over 428 tokens). omega#333 and omega#338 add an +//! opt-in reservation: allocate the buffers once for declared bounds, build and pin every +//! matmul kernel the model will run (`prepare`), then `seal`, after which serving makes no +//! driver allocation inside the bounds and an unprepared kernel or a call past the bounds is +//! refused `TOO_LARGE` by name. //! -//! This module derives the bounds from the model and the daemon's declared limits and makes -//! the one call. It applies only on the path that is already opt-in (Qwen3 on the GB10, -//! `AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1`); the default Qwen3 refusal is untouched. It does not -//! claim to fix #277: it is not proven on the chip, and it does not reserve what omega's -//! header lists as not covered (elementwise scratch, the attention kernel cache, the first -//! build of each matmul shape). +//! This module derives the bounds and the shapes from the model and the daemon's declared +//! limits, and runs reserve, prepare, seal in that order through [`ServingOps`] (the real one +//! calls omega; tests record). It applies only on the path that is already opt-in (Qwen3 on +//! the GB10, `AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1`); the default Qwen3 refusal is untouched. It +//! does not claim to fix #277: it is not proven on the chip, and omega's header lists what is +//! still not covered (elementwise scratch, the attention kernel). use crate::omega_backend::omega_model_refusal_with; use aien_abi_core::ModelConfig; use aien_omega_gpu::{ServingBounds, ServingBytes}; +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; /// omega's contiguous f32 attention kernel refuses `seq_len` past this itself /// (`OMEGA_GPU_ATTN_MAX_GQA_CTX`, omega `src/omega_gpu_attention_api.h:83`), so a larger /// declared context cannot be served natively and is not reserved. pub const GB10_ATTENTION_MAX_CONTEXT: u32 = 4096; -/// Matmul kernel cache depth: 21 distinct (kp, np, grid_x) shapes for Qwen3-4B at the daemon's -/// CTA budget (docs/design/gb10-weight-ownership.md), omega allows at most 32. -pub const GB10_MATMUL_KERNEL_SLOTS: u32 = 32; +/// Matmul kernel cache slots to reserve: omega's maximum (`CACHE_SLOTS_MAX`, omega +/// `src/omega_gpu_matmul_api.c:30`, 128 at 80c4daa). omega picks `grid_x` from the row count, so +/// one weight shape needs several kernels; omega's own sweep of Qwen3-4B (6 shapes x rows 1..256, +/// CTA budget 256) observed 95 distinct kernels (omega#338). Every one is prepared at start-up, +/// so the slots must cover them; `prepare` refuses with TOO_LARGE if they do not. +pub const GB10_MATMUL_KERNEL_SLOTS: u32 = 128; /// What the daemon declares at start-up (aien-cli `run_daemon_server`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -39,11 +47,25 @@ pub struct ServingLimits { pub prefill_chunk_rows: usize, } -/// A reservation that was made: the bounds and the driver bytes omega was asked for. +/// The three omega calls the start-up makes. The real one is [`OmegaServingOps`]. +pub trait ServingOps { + fn reserve(&self, bounds: &ServingBounds) -> Result<(), String>; + /// Build and pin the kernel a call of `m` rows over a `k` x `n` weight will use. + fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String>; + /// From now on an unprepared kernel is refused, never built. + fn seal(&self); +} + +/// A reservation that was made: the bounds, the driver bytes omega was asked for, and what the +/// kernel preparation cost. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ServingReservation { pub bounds: ServingBounds, pub bytes: ServingBytes, + /// Number of `prepare` calls made (rows x distinct weight shapes). + pub prepare_calls: u32, + /// Wall time of the whole reserve, prepare and seal. + pub elapsed: Duration, } impl ServingReservation { @@ -53,7 +75,8 @@ impl ServingReservation { format!( "GB10_SERVING_RESERVATION reserved bytes={} (attention pool {} + q/out {}x2 + table {}; matmul activation {} + result {}) \ bounds: context<={} seqs<={} rows<={} k<={} n<={} logits_n<={} kernel_slots={}; \ - calls past the bounds are refused TOO_LARGE; not covered: elementwise scratch, attention kernel, first build of each matmul shape", + prepared {} matmul kernel calls in {} ms, then sealed; \ + calls past the bounds or unprepared kernels are refused TOO_LARGE; not covered: elementwise scratch, attention kernel", y.total(), y.attention_pool, y.attention_q_out, @@ -67,6 +90,8 @@ impl ServingReservation { b.max_n, b.max_n_one_row, b.kernel_slots, + self.prepare_calls, + self.elapsed.as_millis(), ) } } @@ -78,6 +103,21 @@ fn dim(what: &str, v: usize) -> Result { } } +/// The distinct `(k, n)` weight shapes the forward pass multiplies, from the model config: +/// q (hidden, q_dim), k and v (hidden, kv_dim), o (q_dim, hidden), gate and up (hidden, +/// intermediate), down (intermediate, hidden), and the logits projection (hidden, vocab). +pub fn serving_matmul_shapes(config: &ModelConfig) -> Result, String> { + let h = dim("hidden_dim", config.hidden_dim)?; + let q = dim("q width", config.num_heads * config.head_dim)?; + let kv = dim("kv width", config.num_kv_heads * config.head_dim)?; + let i = dim("intermediate_dim", config.intermediate_dim)?; + let v = dim("vocab_size", config.vocab_size)?; + let set: BTreeSet<(u32, u32)> = [(h, q), (h, kv), (q, h), (h, i), (i, h), (h, v)] + .into_iter() + .collect(); + Ok(set.into_iter().collect()) +} + /// Bounds for `config` under `limits`. Errors name the offending number. pub fn gb10_serving_bounds( config: &ModelConfig, @@ -98,6 +138,10 @@ pub fn gb10_serving_bounds( let context = limits .context_tokens .min(GB10_ATTENTION_MAX_CONTEXT as usize); + let max_rows = dim( + "max rows (max_batch_size, prefill chunk)", + limits.max_batch_rows.max(limits.prefill_chunk_rows), + )?; Ok(ServingBounds { max_context: dim("declared context", context)?, // omega_backend.rs paged_attention_batch runs one chip_paged_one call per sequence. @@ -106,10 +150,7 @@ pub fn gb10_serving_bounds( num_kv_heads: dim("num_kv_heads", config.num_kv_heads)?, head_dim: dim("head_dim", config.head_dim)?, kv_block_size: dim("block_size", config.block_size)?, - max_rows: dim( - "max rows (max_batch_size, prefill chunk)", - limits.max_batch_rows.max(limits.prefill_chunk_rows), - )?, + max_rows, max_k: dim("widest input dimension", max_k)?, max_n: dim("widest output dimension", max_n)?, max_n_one_row: dim("vocab_size", config.vocab_size)?, @@ -117,18 +158,20 @@ pub fn gb10_serving_bounds( }) } -/// [`reserve_gb10_serving`] with the GPU, the opt-in and the reservation call passed in. +/// The start-up sequence, with the GPU, the opt-in and the omega calls passed in. /// -/// `Ok(None)`: the reservation does not apply (not a GB10 build, not Qwen3, or the Qwen3 opt-in -/// is off, in which case the default refusal in `check_model` stops the model before any -/// serving). `Ok(Some(_))`: reserved. `Err(_)`: omega refused the reservation (or a bound could -/// not be formed); the caller must refuse to serve. There is no on-demand fallback. +/// `Ok(None)`: it does not apply (not a GB10 build, not Qwen3, or the Qwen3 opt-in is off, in +/// which case the default refusal in `check_model` stops the model before any serving). +/// `Ok(Some(_))`: reserved, every (rows, shape) kernel prepared, sealed. `Err(_)`: omega refused +/// the reservation or a prepare (or a bound could not be formed); the caller must refuse to +/// serve. There is no on-demand fallback. The reservation is held for the life of the process +/// (omega ends it when it closes the device); this never releases it. pub fn reserve_gb10_serving_with( config: &ModelConfig, limits: &ServingLimits, gpu_native: bool, qwen3_opted_in: bool, - reserve: &dyn Fn(&ServingBounds) -> Result<(), String>, + ops: &dyn ServingOps, ) -> Result, String> { if !gpu_native || !config.qk_norm || omega_model_refusal_with(config, qwen3_opted_in).is_some() { @@ -141,23 +184,111 @@ pub fn reserve_gb10_serving_with( config.model_id ) }; + let started = Instant::now(); let bounds = gb10_serving_bounds(config, limits).map_err(&refuse)?; - reserve(&bounds).map_err(&refuse)?; + let shapes = serving_matmul_shapes(config).map_err(&refuse)?; + ops.reserve(&bounds).map_err(&refuse)?; + let mut prepare_calls = 0u32; + for m in 1..=bounds.max_rows { + for &(k, n) in &shapes { + ops.prepare(m, k, n) + .map_err(|e| refuse(format!("matmul kernel prepare m={m} k={k} n={n}: {e}")))?; + prepare_calls += 1; + } + } + ops.seal(); Ok(Some(ServingReservation { bounds, bytes: bounds.bytes(), + prepare_calls, + elapsed: started.elapsed(), })) } -/// The real reservation call: omega's `omega_gpu_reserve_serving`, with omega's stage text added to -/// a refusal. The daemon passes this to [`reserve_gb10_serving_with`]. -pub fn omega_reserve(b: &ServingBounds) -> Result<(), String> { - aien_omega_gpu::reserve_serving(b).map_err(|e| { - let stage = aien_omega_gpu::last_error(); - if stage.is_empty() { - e.to_string() - } else { - format!("{e} (omega: {stage})") +/// The real calls: omega's `omega_gpu_reserve_serving`, `omega_gpu_matmul_prepare` and +/// `omega_gpu_serving_seal`, with omega's stage text added to a refusal. +pub struct OmegaServingOps; + +fn with_stage(e: aien_omega_gpu::OmegaGpuError) -> String { + let stage = aien_omega_gpu::last_error(); + if stage.is_empty() { + e.to_string() + } else { + format!("{e} (omega: {stage})") + } +} + +impl ServingOps for OmegaServingOps { + fn reserve(&self, b: &ServingBounds) -> Result<(), String> { + aien_omega_gpu::reserve_serving(b).map_err(with_stage) + } + fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String> { + aien_omega_gpu::matmul_prepare(m, k, n).map_err(with_stage) + } + fn seal(&self) { + aien_omega_gpu::seal_serving(); + } +} + +/// Reads the serving log lines the daemon prints next to `GB10_SERVING_RESERVATION`: the +/// allocation counters once after warm-up, and the change since warm-up after every request. +/// A nonzero change is printed loudly, never hidden. +pub trait ServingProbe: Send + Sync { + /// Called once, after the declared warm-up and before the first request is accepted. + fn after_warm_up(&self) -> Option; + /// Called after each served connection. + fn after_request(&self) -> Option; +} + +/// [`ServingProbe`] over omega's allocation counters (`omega_gpu_session_alloc_stats`). +/// Counters are cumulative for the process, so overlapping requests cannot confuse the delta. +pub struct AllocProbe { + read: Box Option + Send + Sync>, + baseline: std::sync::Mutex>, +} + +impl AllocProbe { + pub fn new(read: Box Option + Send + Sync>) -> Self { + Self { + read, + baseline: std::sync::Mutex::new(None), } - }) + } + + /// The probe on omega's real counters. + pub fn omega() -> Self { + Self::new(Box::new(aien_omega_gpu::alloc_stats)) + } +} + +impl ServingProbe for AllocProbe { + fn after_warm_up(&self) -> Option { + let s = (self.read)()?; + *self.baseline.lock().ok()? = Some(s); + Some(format!( + "GB10_SERVING_ALLOC after_warmup allocs={} bytes={} failures={} frees={}", + s.allocs, s.alloc_bytes, s.alloc_failures, s.frees + )) + } + + fn after_request(&self) -> Option { + let now = (self.read)()?; + let base = (*self.baseline.lock().ok()?)?; + let d = |a: u64, b: u64| a.saturating_sub(b); + let (allocs, bytes, failures, frees) = ( + d(now.allocs, base.allocs), + d(now.alloc_bytes, base.alloc_bytes), + d(now.alloc_failures, base.alloc_failures), + d(now.frees, base.frees), + ); + // Frees alone are not an allocation, but a free after warm-up means a buffer was replaced. + let flag = if allocs != 0 || failures != 0 || frees != 0 { + " NONZERO: serving asked the driver for memory after warm-up" + } else { + "" + }; + Some(format!( + "GB10_SERVING_ALLOC request allocs_since_warmup={allocs} bytes_since_warmup={bytes} failures_since_warmup={failures} frees_since_warmup={frees}{flag}" + )) + } } diff --git a/crates/aien-inference-abi/tests/gb10_serving_reservation.rs b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs index b3315a68..d5524957 100644 --- a/crates/aien-inference-abi/tests/gb10_serving_reservation.rs +++ b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs @@ -1,11 +1,14 @@ //! sovereign-core#277 (cut toward it, not a fix): when the daemon serves Qwen3 on the GB10 -//! (the already opt-in path), start-up reserves the serving buffers once, from declared -//! bounds, and refuses to serve by name when omega refuses. CPU only: the reservation call is -//! injected, nothing touches a driver. -use aien_inference_abi::gb10_serving::{reserve_gb10_serving_with, ServingLimits}; +//! (the already opt-in path), start-up reserves the serving buffers from declared bounds, +//! prepares every matmul kernel, seals, and refuses to serve by name when omega refuses. +//! CPU only: the omega calls are injected, nothing touches a driver. The daemon-level ordering +//! tests (prepare of every rows x shape, seal last) live in aien-cli `commands.rs`. +use aien_inference_abi::gb10_serving::{ + reserve_gb10_serving_with, serving_matmul_shapes, ServingLimits, ServingOps, +}; use aien_inference_abi::model_config_from_hf_json; use aien_omega_gpu::ServingBounds; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::path::PathBuf; fn qwen3_4b() -> aien_inference_abi::ModelConfig { @@ -17,8 +20,7 @@ fn qwen3_4b() -> aien_inference_abi::ModelConfig { model_config_from_hf_json("Qwen/Qwen3-4B-Instruct-2507", &cfg, Some(&gen)).unwrap() } -/// The daemon's declared limits (aien-cli run_daemon_server: max_batch_size 256, prefill chunk -/// 128, arena 4096), with the KV pool planned for 4096 tokens. +/// The daemon's declared limits (max_batch_size 256, prefill chunk 128, arena 4096). fn daemon_limits() -> ServingLimits { ServingLimits { context_tokens: 4096, @@ -27,16 +29,39 @@ fn daemon_limits() -> ServingLimits { } } -#[test] -fn qwen3_on_gb10_reserves_once_before_serving_with_the_declared_bounds() { - let calls: RefCell> = RefCell::new(Vec::new()); - let got = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &|b| { - calls.borrow_mut().push(*b); +#[derive(Default)] +struct Ops { + reserved: RefCell>, + prepares: Cell, + seals: Cell, + refuse_reserve: bool, +} + +impl ServingOps for Ops { + fn reserve(&self, b: &ServingBounds) -> Result<(), String> { + self.reserved.borrow_mut().push(*b); + if self.refuse_reserve { + Err("omega_gpu rc=-4 (CHIP_FAIL) (stage: nvrm_alloc scratch)".to_string()) + } else { + Ok(()) + } + } + fn prepare(&self, _m: u32, _k: u32, _n: u32) -> Result<(), String> { + self.prepares.set(self.prepares.get() + 1); Ok(()) - }) - .expect("reserved") - .expect("Qwen3 on GB10 must reserve"); - let calls = calls.into_inner(); + } + fn seal(&self) { + self.seals.set(self.seals.get() + 1); + } +} + +#[test] +fn qwen3_on_gb10_reserves_once_with_the_declared_bounds() { + let ops = Ops::default(); + let got = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &ops) + .expect("reserved") + .expect("Qwen3 on GB10 must reserve"); + let calls = ops.reserved.borrow(); assert_eq!(calls.len(), 1, "exactly one reservation call"); let b = calls[0]; assert_eq!(got.bounds, b); @@ -54,58 +79,119 @@ fn qwen3_on_gb10_reserves_once_before_serving_with_the_declared_bounds() { assert_eq!(b.max_k, 9728, "down_proj input is the intermediate size"); assert_eq!(b.max_n_one_row, 151936, "the logits projection"); assert!(b.max_n >= 9728); - assert!( - b.kernel_slots >= 21, - "21 distinct matmul shapes for Qwen3-4B (design note)" + // omega's own sweep (omega#338, fake layer): Qwen3-4B needs 95 distinct kernels, so the 32 + // slots of omega#333 are not enough; 128 is omega's maximum. + assert_eq!(b.kernel_slots, 128); + assert_eq!( + got.bytes.total(), + 194_170_880, + "bytes asked for the daemon bounds" + ); + assert_eq!((ops.prepares.get(), ops.seals.get()), (256 * 6, 1)); + assert_eq!(got.prepare_calls, 256 * 6); +} + +#[test] +fn shapes_come_from_the_model_config() { + let c = qwen3_4b(); + let s = serving_matmul_shapes(&c).unwrap(); + assert_eq!( + s, + vec![ + (2560, 1024), + (2560, 4096), + (2560, 9728), + (2560, 151936), + (4096, 2560), + (9728, 2560) + ] ); - assert!(got.bytes.total() > 0); } #[test] fn context_is_the_smaller_of_the_kv_plan_and_the_attention_limit() { - let seen = RefCell::new(Vec::new()); - let rec = |b: &ServingBounds| { - seen.borrow_mut().push(b.max_context); - Ok(()) - }; - let mut l = daemon_limits(); - l.context_tokens = 2048; - reserve_gb10_serving_with(&qwen3_4b(), &l, true, true, &rec).unwrap(); - l.context_tokens = 262144; // the model's own declared context: omega's f32 attention stops at 4096 - reserve_gb10_serving_with(&qwen3_4b(), &l, true, true, &rec).unwrap(); - assert_eq!(*seen.borrow(), vec![2048, 4096]); + let mut seen = Vec::new(); + for ctx in [2048usize, 262144] { + let ops = Ops::default(); + let mut l = daemon_limits(); + l.context_tokens = ctx; + reserve_gb10_serving_with(&qwen3_4b(), &l, true, true, &ops).unwrap(); + seen.push(ops.reserved.borrow()[0].max_context); + } + assert_eq!(seen, vec![2048, 4096]); } #[test] fn a_refusal_stops_serving_by_name_with_no_fallback() { - let err = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &|_| { - Err("omega_gpu rc=-4 (CHIP_FAIL) (stage: nvrm_alloc scratch)".to_string()) - }) - .expect_err("a refused reservation must refuse to serve"); + let ops = Ops { + refuse_reserve: true, + ..Ops::default() + }; + let err = reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, true, &ops) + .expect_err("a refused reservation must refuse to serve"); assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}"); assert!(err.contains("CHIP_FAIL"), "names omega's reason: {err}"); assert!(err.contains("sovereign-core#277"), "{err}"); assert!(err.contains("no on-demand fallback"), "{err}"); + assert_eq!((ops.prepares.get(), ops.seals.get()), (0, 0)); } #[test] fn nothing_changes_off_the_opt_in_qwen3_gb10_path() { - let never = |_: &ServingBounds| -> Result<(), String> { panic!("must not reserve") }; - // not native (CPU daemon): no call + let none = |native: bool, opted: bool, cfg: &aien_inference_abi::ModelConfig| { + let ops = Ops::default(); + let r = reserve_gb10_serving_with(cfg, &daemon_limits(), native, opted, &ops).unwrap(); + assert!(r.is_none()); + assert!( + ops.reserved.borrow().is_empty() && ops.prepares.get() == 0 && ops.seals.get() == 0 + ); + }; + none(false, true, &qwen3_4b()); // not native (CPU daemon) + none(true, false, &qwen3_4b()); // default refusal still in force (no opt-in) + let mut llama = qwen3_4b(); + llama.qk_norm = false; // a non-Qwen3 model on the GB10 is untouched + none(true, true, &llama); +} + +#[test] +fn the_alloc_probe_logs_the_baseline_and_shows_any_nonzero_delta() { + use aien_inference_abi::gb10_serving::{AllocProbe, ServingProbe}; + use aien_omega_gpu::AllocStats; + use std::sync::{Arc, Mutex}; + let now = Arc::new(Mutex::new(AllocStats { + allocs: 600, + alloc_bytes: 7_000_000_000, + alloc_failures: 0, + frees: 12, + })); + let n2 = now.clone(); + let p = AllocProbe::new(Box::new(move || Some(*n2.lock().unwrap()))); assert_eq!( - reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), false, true, &never).unwrap(), - None + p.after_request(), + None, + "no line before the warm-up baseline" ); - // default refusal still in force (no opt-in): the reservation is not what serves it assert_eq!( - reserve_gb10_serving_with(&qwen3_4b(), &daemon_limits(), true, false, &never).unwrap(), - None + p.after_warm_up().unwrap(), + "GB10_SERVING_ALLOC after_warmup allocs=600 bytes=7000000000 failures=0 frees=12" ); - // a non-Qwen3 model on the GB10 is untouched - let mut llama = qwen3_4b(); - llama.qk_norm = false; - assert_eq!( - reserve_gb10_serving_with(&llama, &daemon_limits(), true, true, &never).unwrap(), - None + let quiet = p.after_request().unwrap(); + assert!( + quiet.contains("allocs_since_warmup=0") && !quiet.contains("NONZERO"), + "{quiet}" + ); + now.lock().unwrap().allocs += 3; + now.lock().unwrap().alloc_bytes += 12288; + now.lock().unwrap().alloc_failures += 1; + let loud = p.after_request().unwrap(); + assert!(loud.contains("allocs_since_warmup=3"), "{loud}"); + assert!(loud.contains("bytes_since_warmup=12288"), "{loud}"); + assert!(loud.contains("failures_since_warmup=1"), "{loud}"); + assert!( + loud.contains("NONZERO"), + "a nonzero delta must be visible: {loud}" ); + // the stub build has no counters: the probe stays silent rather than inventing zeros + let none = AllocProbe::new(Box::new(|| None)); + assert_eq!((none.after_warm_up(), none.after_request()), (None, None)); } diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index a30e1efb..d64335b1 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -81,7 +81,16 @@ impl OmegaGpuMatmulInfo { pub struct OmegaGpuTensor { _private: [u8; 0], } -#[cfg(has_omega_gpu)] +/// omega `OmegaGpuAllocStats` (`src/omega_gpu_session.h`), field for field. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct OmegaGpuAllocStats { + pub allocs: u64, + pub alloc_bytes: u64, + pub alloc_failures: u64, + pub frees: u64, +} + /// omega `OmegaGpuServingBounds` (`src/omega_gpu_serving.h`), field for field. #[repr(C)] #[derive(Debug, Clone, Copy)] @@ -166,6 +175,12 @@ extern "C" { // OMEGA_GPU_ATTN_* code (omega_gpu_matmul_last_error() has the text). pub fn omega_gpu_reserve_serving(b: *const OmegaGpuServingBounds) -> c_int; pub fn omega_gpu_serving_release(); + // omega c1/lib-serving 80c4daa (omega#338): build and pin the kernel one call shape will use; + // then seal so any unprepared kernel is refused TOO_LARGE with no driver call. + pub fn omega_gpu_matmul_prepare(m: u32, k: u32, n: u32) -> c_int; + pub fn omega_gpu_serving_seal(); + // omega c1/lib-serving bc9fa71 `src/omega_gpu_session.h`: process-wide driver allocation counters. + pub fn omega_gpu_session_alloc_stats(out: *mut OmegaGpuAllocStats); } // ---- omega `src/omega_gpu_elementwise_api.h` (FB-1 cut 4, pinned 2636409) ---- diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index f0af5bc9..72cdc102 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -1006,7 +1006,55 @@ pub fn reserve_serving(b: &ServingBounds) -> Result<(), OmegaGpuError> { } } -/// Lift the reservation (buffers stay, growth is allowed again). No-op in the stub. +/// Driver allocation counters since the process started (omega `omega_gpu_session_alloc_stats`). +pub use ffi::OmegaGpuAllocStats as AllocStats; + +/// Read omega's allocation counters; `None` in the stub (no engine, nothing allocates). +pub fn alloc_stats() -> Option { + #[cfg(has_omega_gpu)] + { + let mut s = AllocStats::default(); + // SAFETY: `s` is a valid repr(C) struct that omega fills; no lock is held across the call. + unsafe { ffi::omega_gpu_session_alloc_stats(&mut s) }; + Some(s) + } + #[cfg(not(has_omega_gpu))] + None +} + +/// Build and pin the matmul kernel a call of `m` rows over a `k` x `n` weight will use (omega +/// `omega_gpu_matmul_prepare`). Stub: `Unavailable`. +pub fn matmul_prepare(m: u32, k: u32, n: u32) -> Result<(), OmegaGpuError> { + #[cfg(has_omega_gpu)] + { + // SAFETY: plain integer arguments; omega takes its own lock. + let rc = unsafe { ffi::omega_gpu_matmul_prepare(m, k, n) }; + if rc == 0 { + Ok(()) + } else { + Err(rc_error(rc)) + } + } + #[cfg(not(has_omega_gpu))] + { + let _ = (m, k, n); + Err(OmegaGpuError::Unavailable) + } +} + +/// Seal the serving state: from now on a matmul kernel that was not prepared is refused, never +/// built (omega `omega_gpu_serving_seal`). No-op in the stub. +pub fn seal_serving() { + #[cfg(has_omega_gpu)] + // SAFETY: no arguments; omega takes its own lock. + unsafe { + ffi::omega_gpu_serving_seal(); + } +} + +/// Lift the reservation and the seal (buffers stay, growth is allowed again). The daemon never +/// calls this: the reservation is held for the life of the process and ends when omega closes +/// the device at exit. No-op in the stub. pub fn release_serving() { #[cfg(has_omega_gpu)] // SAFETY: no arguments; omega takes its own lock. diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 9eaa18af..ef585e63 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -29,6 +29,8 @@ pub struct AienRuntimeServer { is_running: Arc, tokenizer: Arc>>, warm_up: AtomicBool, + /// Optional serving-time probe (GB10 allocation counters), see `set_serving_probe`. + probe: std::sync::Mutex>>, /// Test seam: a ready-made compose bridge (see `with_compose_bridge`). compose_override: std::sync::Mutex>>, /// The loaded model files' digests (set by the daemon after load; absent @@ -59,6 +61,7 @@ impl AienRuntimeServer { is_running: Arc::new(AtomicBool::new(false)), tokenizer: Arc::new(RwLock::new(None)), warm_up: AtomicBool::new(false), + probe: std::sync::Mutex::new(None), compose_override: std::sync::Mutex::new(None), identity: std::sync::Mutex::new(None), started: DaemonStart::now(), @@ -92,6 +95,15 @@ impl AienRuntimeServer { self.warm_up.store(true, Ordering::SeqCst); } + /// Log the GB10 allocation counters once after warm-up and the change since warm-up after + /// every served connection (sovereign-core#277). Unset = nothing is logged. + pub fn set_serving_probe( + &self, + probe: Arc, + ) { + *self.probe.lock().expect("probe lock") = Some(probe); + } + pub fn spine(&self) -> Arc> { self.spine.clone() } @@ -195,6 +207,10 @@ impl AienRuntimeServer { if self.warm_up.load(Ordering::SeqCst) { println!(" {}", self.run_warm_up().await); } + let probe = self.probe.lock().expect("probe lock").clone(); + if let Some(line) = probe.as_ref().and_then(|p| p.after_warm_up()) { + println!(" {line}"); + } // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). let preset = self @@ -305,6 +321,7 @@ impl AienRuntimeServer { let compose_conn = compose.clone(); let identity_conn = identity.clone(); let started = self.started; + let probe_conn = probe.clone(); tokio::spawn(async move { handle_connection( stream, @@ -316,6 +333,9 @@ impl AienRuntimeServer { (identity_conn, started), ) .await; + if let Some(line) = probe_conn.as_ref().and_then(|p| p.after_request()) { + println!(" {line}"); + } }); } Err(e) => { diff --git a/omega.lock b/omega.lock index 8ef18135..a7ecb48e 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -235564d5060857e46f2e7b4c25c673d0054afb14 +3b11eb0d656efcbfe6a30819314518422f990287 From 5c437a594e9425ef1c3bdead5aa1ca3246ddc311 Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 21:37:51 -0500 Subject: [PATCH 5/7] Pin omega to the #338 merge commit 6c6180cf; kernel slot comment says 128 The merge commit's tree equals the reviewed head 3b11eb0 (dfe045f). Co-Authored-By: Claude Opus 5.5 --- crates/aien-omega-gpu/src/lib.rs | 2 +- omega.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 72cdc102..d3163612 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -907,7 +907,7 @@ pub struct ServingBounds { pub max_n: u32, /// Widest output dimension for calls of at most 16 rows (the logits projection). pub max_n_one_row: u32, - /// Matmul kernel cache slots (omega allows at most 32). + /// Matmul kernel cache slots (omega allows at most 128, CACHE_SLOTS_MAX). pub kernel_slots: u32, } diff --git a/omega.lock b/omega.lock index a7ecb48e..ec304e42 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -3b11eb0d656efcbfe6a30819314518422f990287 +6c6180cf378075b61291f4565d226eba38b4decd From 83848897244a6daa64f67d3b676db072cb104563 Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 23:29:39 -0500 Subject: [PATCH 6/7] GB10 alloc probe: a frees-only delta is flagged FREES, not as an allocation m311 (declared GB10 run) showed frees_since_warmup=33 with zero allocations on the Shutdown connection of the restart leg, labelled 'asked the driver for memory'. Allocations and failures keep the NONZERO flag; frees alone get their own name. Test covers the frees-only case. Co-Authored-By: Claude Opus 5.5 --- crates/aien-inference-abi/src/gb10_serving.rs | 7 +++++-- .../aien-inference-abi/tests/gb10_serving_reservation.rs | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/aien-inference-abi/src/gb10_serving.rs b/crates/aien-inference-abi/src/gb10_serving.rs index 3c04ff5c..637a20f2 100644 --- a/crates/aien-inference-abi/src/gb10_serving.rs +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -281,9 +281,12 @@ impl ServingProbe for AllocProbe { d(now.alloc_failures, base.alloc_failures), d(now.frees, base.frees), ); - // Frees alone are not an allocation, but a free after warm-up means a buffer was replaced. - let flag = if allocs != 0 || failures != 0 || frees != 0 { + // Frees alone are not an allocation, but a free after warm-up means a buffer was replaced + // (or the daemon is tearing down), so it is flagged too, under its own name. + let flag = if allocs != 0 || failures != 0 { " NONZERO: serving asked the driver for memory after warm-up" + } else if frees != 0 { + " FREES: driver memory released after warm-up (teardown, or a buffer was replaced)" } else { "" }; diff --git a/crates/aien-inference-abi/tests/gb10_serving_reservation.rs b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs index d5524957..2b755a01 100644 --- a/crates/aien-inference-abi/tests/gb10_serving_reservation.rs +++ b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs @@ -180,6 +180,15 @@ fn the_alloc_probe_logs_the_baseline_and_shows_any_nonzero_delta() { quiet.contains("allocs_since_warmup=0") && !quiet.contains("NONZERO"), "{quiet}" ); + // frees alone (teardown) are flagged under their own name, never as an allocation + now.lock().unwrap().frees += 33; + let freed = p.after_request().unwrap(); + assert!( + freed.contains("frees_since_warmup=33") + && freed.contains("FREES:") + && !freed.contains("NONZERO"), + "{freed}" + ); now.lock().unwrap().allocs += 3; now.lock().unwrap().alloc_bytes += 12288; now.lock().unwrap().alloc_failures += 1; From 0be50fbf46919a5f4a5a8489341109b3a2539b57 Mon Sep 17 00:00:00 2001 From: aien Date: Wed, 7 Oct 2026 23:39:57 -0500 Subject: [PATCH 7/7] crumb compile Co-Authored-By: Claude Opus 5.5 --- .crumb | 10 +++++----- crates/aien-cli/.crumb | 14 +++++++------- crates/aien-cli/src/.crumb | 8 ++++---- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.crumb b/.crumb index 88d23072..5a5bb992 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:2773d5ada0e6ae8b446499314f4a704361ab91a14a35259a62607b7c731d0ab9", - "compiled_at": "2026-10-08T04:19:10Z", + "compiled_at": "2026-10-08T04:40:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:ab3b19ba72dfcb9a077abfaf1a39bdbaa3876bfcc9aee8345b44477d9e5756b3", + "digest": "sha256:85279ff903a1f2a9d0e02907fe8973949efc945cb2219cf0e5101e876f7298a2", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1352, - "generated_at_commit": "7e1e78cec04b6fc751e7377abc1d47bb414396cd", - "source_tree": "sha256:24a769aebf8bda35900e7ee22233147dae076d8beeb41aa5b29bbc6e965f1bfb" + "files": 1354, + "generated_at_commit": "20e976a55907c12fbfb65c32198bea55713f4eb4", + "source_tree": "sha256:d7c4f0132aa911c95f8e6f49e88883c7a948c75983b8fb2555892195982222b8" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 2e10ee57..249b8216 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "9c9ce8f6344cbbad6542a9a1bdac9a2b1d041c8c8222e52098bd5d9f3297f3b5", - "last_commit": "b833922", + "digest": "48d2f54653f8fa475db1fbfcd2471a54bfb9f9df1d186ebbc5bf04cd7b031238", + "last_commit": "9b84bb5", "name": "src", "purpose": "" } ], - "children_root": "sha256:63c3745948dc2befd2e58e75a0645ba14343222b85017dbfe3aa46daf352258f", - "compiled_at": "2026-10-08T02:43:12Z", + "children_root": "sha256:beb8815bbfa7560638ea9f42f268ac6fdc52611dcca61092bb487e645c2b4178", + "compiled_at": "2026-10-08T04:29:50Z", "compiler": "crumb-compile/1", - "digest": "sha256:9463d27a0b504ddaf99f2c27eb2fbae669b6b55cae96c10fff854c84a39098de", + "digest": "sha256:67a8418774bb6965ee07da0a9cff8e74a76b09d29ed8534eef59249280b39d73", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 31, - "generated_at_commit": "b8339222d3357851cde0c93f5176b0491467be79", - "source_tree": "sha256:d12dd103203d1f976073ad2ac115a3ead4511e5eba7f6cd8f1ba3d14f267fcdf" + "generated_at_commit": "45074e89b1d48f92f29e8b8bc99b1faaf5cced97", + "source_tree": "sha256:cde8d6c8cbfebf82cd1d8a92d1292fe747403c49a2ae16fddf41e4c343129915" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 60c71ad3..4e43d3d6 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-08T02:43:12Z", + "compiled_at": "2026-10-08T04:29:50Z", "compiler": "crumb-compile/1", - "digest": "sha256:9c9ce8f6344cbbad6542a9a1bdac9a2b1d041c8c8222e52098bd5d9f3297f3b5", + "digest": "sha256:48d2f54653f8fa475db1fbfcd2471a54bfb9f9df1d186ebbc5bf04cd7b031238", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 26, - "generated_at_commit": "b8339222d3357851cde0c93f5176b0491467be79", - "source_tree": "sha256:1f78a0655e2829c2cf2010f71be1c8f198e750da2dd0e12214316d748321234b" + "generated_at_commit": "45074e89b1d48f92f29e8b8bc99b1faaf5cced97", + "source_tree": "sha256:0cd55b8e17fc8fdcf77a99cd19a867784106dab7f3eb4284e7e6ed458e322614" } }, "history": [