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
GitHub aien-dev/aien-sovereign-core-mv#311 (code only)
Apply it
git checkout -b patch-8f21ee53cfc83e30 9d1cb549105e4aaadcbc18a8ca2851b52044a215 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/8f21ee53cfc83e30.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
311
0be50fbf46919a5f4a5a8489341109b3a2539b57
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":311,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/311","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:46Z","metadata":"unavailable","state_derived":true}
Changes
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": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 57fb5f79..ce0f9385 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1490,6 +1490,47 @@ fn apply_omega_cta_budget(budget: Option<aien_omega_gpu::CtaBudget>) -> Result<S )) } +/// The scheduler limits the daemon declares. One definition for `run_daemon_server` and the tests +/// of the GB10 serving reservation, whose bounds (decode rows, prefill chunk) come from it. +fn daemon_scheduler_config() -> 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 +/// 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, + kv_context_tokens: usize, + sched: &aien_scheduler::SchedulerConfig, + gpu_native: bool, + qwen3_opted_in: bool, + ops: &dyn aien_inference_abi::gb10_serving::ServingOps, +) -> Result<Option<String>, 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, + ops, + ) + .map(|r| r.map(|r| r.log_line())) +} + pub async fn run_daemon_server() { println!( "{}", @@ -1502,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() { @@ -1525,6 +1559,8 @@ 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 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) => { @@ -1563,7 +1599,37 @@ 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. + let mut serving_probe: Option< + std::sync::Arc<dyn aien_inference_abi::gb10_serving::ServingProbe>, + > = None; + match daemon_serving_reservation( + &model_config, + _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::OmegaServingOps, + ) { + 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()); + std::process::exit(1); + } + } 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()); @@ -1964,6 +2030,198 @@ 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() + } + + 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<Vec<Ev>>, + fail_prepare_at: Option<usize>, + 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<Option<String>, String> { + daemon_serving_reservation( + &qwen3_4b_config(), + ctx, + &daemon_scheduler_config(), + native, + opted_in, + rec, + ) + } + + #[test] + 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( + &cfg, + Some(2048), + &|| Ok(u64::MAX), + false, + ) + .unwrap(); + 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::<std::collections::BTreeSet<_>>(), + 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}" + ); + } + + #[test] + 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 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!( + 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!(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] 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 new file mode 100644 index 00000000..637a20f2 --- /dev/null +++ b/crates/aien-inference-abi/src/gb10_serving.rs @@ -0,0 +1,297 @@ +//! 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 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 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 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)] +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, +} + +/// 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 { + /// 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={}; \ + 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, + 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, + self.prepare_calls, + self.elapsed.as_millis(), + ) + } +} + +fn dim(what: &str, v: usize) -> Result<u32, String> { + match u32::try_from(v) { + Ok(x) if x > 0 => Ok(x), + _ => Err(format!("{what} = {v} is not a usable serving bound")), + } +} + +/// 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<Vec<(u32, u32)>, 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, + limits: &ServingLimits, +) -> Result<ServingBounds, String> { + 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); + 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. + 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, + 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, + }) +} + +/// The start-up sequence, with the GPU, the opt-in and the omega calls passed in. +/// +/// `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, + ops: &dyn ServingOps, +) -> Result<Option<ServingReservation>, 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 started = Instant::now(); + let bounds = gb10_serving_bounds(config, limits).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 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<String>; + /// Called after each served connection. + fn after_request(&self) -> Option<String>; +} + +/// [`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<dyn Fn() -> Option<aien_omega_gpu::AllocStats> + Send + Sync>, + baseline: std::sync::Mutex<Option<aien_omega_gpu::AllocStats>>, +} + +impl AllocProbe { + pub fn new(read: Box<dyn Fn() -> Option<aien_omega_gpu::AllocStats> + 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<String> { + 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<String> { + 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 + // (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 { + "" + }; + 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/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/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<String> { /// 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-inference-abi/tests/gb10_serving_reservation.rs b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs new file mode 100644 index 00000000..2b755a01 --- /dev/null +++ b/crates/aien-inference-abi/tests/gb10_serving_reservation.rs @@ -0,0 +1,206 @@ +//! 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 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::{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 (max_batch_size 256, prefill chunk 128, arena 4096). +fn daemon_limits() -> ServingLimits { + ServingLimits { + context_tokens: 4096, + max_batch_rows: 256, + prefill_chunk_rows: 128, + } +} + +#[derive(Default)] +struct Ops { + reserved: RefCell<Vec<ServingBounds>>, + prepares: Cell<u32>, + seals: Cell<u32>, + 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(()) + } + 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); + 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); + // 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) + ] + ); +} + +#[test] +fn context_is_the_smaller_of_the_kv_plan_and_the_attention_limit() { + 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 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 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!( + p.after_request(), + None, + "no line before the warm-up baseline" + ); + assert_eq!( + p.after_warm_up().unwrap(), + "GB10_SERVING_ALLOC after_warmup allocs=600 bytes=7000000000 failures=0 frees=12" + ); + let quiet = p.after_request().unwrap(); + assert!( + 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; + 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 2a94bb43..d64335b1 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -81,6 +81,32 @@ impl OmegaGpuMatmulInfo { pub struct OmegaGpuTensor { _private: [u8; 0], } +/// 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)] +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,6 +170,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 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 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 02b40887..d3163612 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -883,6 +883,186 @@ 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 128, CACHE_SLOTS_MAX). + 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 { + // 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; + 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 = 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; + 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: round_up(per_seq * seqs, 4096), + attention_q_out: round_up(qo, 4096), + attention_table: table, + matmul_activation: round_up(mp * kp * 2, 4096), + matmul_result: round_up(c, 4096), + } + } +} + +/// 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)] + { + 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, + }; + // 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)) + } + } + #[cfg(not(has_omega_gpu))] + { + let _ = b; + Err(OmegaGpuError::Unavailable) + } +} + +/// 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<AllocStats> { + #[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. + unsafe { + ffi::omega_gpu_serving_release(); + } +} + #[cfg(test)] mod cta_budget_tests { use super::*; @@ -1014,6 +1194,51 @@ 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, 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 + 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/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<AtomicBool>, tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, warm_up: AtomicBool, + /// Optional serving-time probe (GB10 allocation counters), see `set_serving_probe`. + probe: std::sync::Mutex<Option<Arc<dyn aien_inference_abi::gb10_serving::ServingProbe>>>, /// Test seam: a ready-made compose bridge (see `with_compose_bridge`). compose_override: std::sync::Mutex<Option<Arc<ComposeBridge>>>, /// 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<dyn aien_inference_abi::gb10_serving::ServingProbe>, + ) { + *self.probe.lock().expect("probe lock") = Some(probe); + } + pub fn spine(&self) -> Arc<Mutex<AienRuntimeSpine>> { 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/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. diff --git a/omega.lock b/omega.lock index b8b87611..ec304e42 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -01f6a74636b8383b010cdb95597839582c415c27 +6c6180cf378075b61291f4565d226eba38b4decd