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
aien-sovereign-core-mv / crates / aien-inference-abi / src / gb10_serving.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Start-up reservation of the GB10 serving buffers and kernels (sovereign-core#277, a cut |
| 17 | //! toward it). |
| 18 | //! |
| 19 | //! Without it, omega grows the attention staging pool, the matmul activation/result buffers |
| 20 | //! and the matmul kernel cache on demand while serving, and every growth is a driver (RM) |
| 21 | //! allocation that can fail with NV_ERR_NO_MEMORY when MemFree is low (omega#327; omega#332 |
| 22 | //! measured 458 allocations and 456 frees over 428 tokens). omega#333 and omega#338 add a |
| 23 | //! reservation: allocate the buffers once for declared bounds, build and pin every |
| 24 | //! matmul kernel the model will run (`prepare`), then `seal`, after which serving makes no |
| 25 | //! driver allocation inside the bounds and an unprepared kernel or a call past the bounds is |
| 26 | //! refused `TOO_LARGE` by name. |
| 27 | //! |
| 28 | //! This module derives the bounds and the shapes from the model and the daemon's declared |
| 29 | //! limits, and runs reserve, prepare, seal in that order through [`ServingOps`] (the real one |
| 30 | //! calls omega; tests record). It applies only to Qwen3 on the GB10, which is enabled by |
| 31 | //! default since #277 on a production-strict run (`AIEN_GB10_QWEN3_DECLARED_ATTEMPT=0` refuses it; |
| 32 | //! `1` also enables it under `AIEN_DEV_FALLBACK=1`). Evidence: #277 attempt 3 passed |
| 33 | //! (https://github.com/aien-spark/aien-sovereign-core/issues/277#issuecomment-6059774846), limited to a |
| 34 | //! Linux-hosted GB10 (not native Aienux), one prompt, context 4096, no endurance run and no |
| 35 | //! failing baseline. It does not claim to fix #277 beyond that, and omega's header lists what is |
| 36 | //! still not covered (elementwise scratch, the attention kernel). |
| 37 | |
| 38 | use crate::omega_backend::omega_model_refusal_with; |
| 39 | use aien_abi_core::ModelConfig; |
| 40 | use aien_omega_gpu::{ServingBounds, ServingBytes}; |
| 41 | use std::collections::BTreeSet; |
| 42 | use std::time::{Duration, Instant}; |
| 43 | |
| 44 | /// omega's contiguous f32 attention kernel refuses `seq_len` past this itself |
| 45 | /// (`OMEGA_GPU_ATTN_MAX_GQA_CTX`, omega `src/omega_gpu_attention_api.h:83`), so a larger |
| 46 | /// declared context cannot be served natively and is not reserved. |
| 47 | pub const GB10_ATTENTION_MAX_CONTEXT: u32 = 4096; |
| 48 | |
| 49 | /// Matmul kernel cache slots to reserve: omega's maximum (`CACHE_SLOTS_MAX`, omega |
| 50 | /// `src/omega_gpu_matmul_api.c:30`, 128 at 80c4daa). omega picks `grid_x` from the row count, so |
| 51 | /// one weight shape needs several kernels; omega's own sweep of Qwen3-4B (6 shapes x rows 1..256, |
| 52 | /// CTA budget 256) observed 95 distinct kernels (omega#338). Every one is prepared at start-up, |
| 53 | /// so the slots must cover them; `prepare` refuses with TOO_LARGE if they do not. |
| 54 | pub const GB10_MATMUL_KERNEL_SLOTS: u32 = 128; |
| 55 | |
| 56 | /// What the daemon declares at start-up (aien-cli `run_daemon_server`). |
| 57 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 58 | pub struct ServingLimits { |
| 59 | /// Context the KV pool is planned for (`KvPoolPlan::context_tokens`). |
| 60 | pub context_tokens: usize, |
| 61 | /// Most sequences one decode step batches (`SchedulerConfig::max_batch_size`); the batched |
| 62 | /// decode path runs every projection with this many rows. |
| 63 | pub max_batch_rows: usize, |
| 64 | /// Prompt tokens per prefill chunk (`SchedulerConfig::prefill_chunk_size`). |
| 65 | pub prefill_chunk_rows: usize, |
| 66 | } |
| 67 | |
| 68 | /// The three omega calls the start-up makes. The real one is [`OmegaServingOps`]. |
| 69 | pub trait ServingOps { |
| 70 | fn reserve(&self, bounds: &ServingBounds) -> Result<(), String>; |
| 71 | /// Build and pin the kernel a call of `m` rows over a `k` x `n` weight will use. |
| 72 | fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String>; |
| 73 | /// From now on an unprepared kernel is refused, never built. |
| 74 | fn seal(&self); |
| 75 | } |
| 76 | |
| 77 | /// A reservation that was made: the bounds, the driver bytes omega was asked for, and what the |
| 78 | /// kernel preparation cost. |
| 79 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 80 | pub struct ServingReservation { |
| 81 | pub bounds: ServingBounds, |
| 82 | pub bytes: ServingBytes, |
| 83 | /// Number of `prepare` calls made (rows x distinct weight shapes). |
| 84 | pub prepare_calls: u32, |
| 85 | /// Wall time of the whole reserve, prepare and seal. |
| 86 | pub elapsed: Duration, |
| 87 | } |
| 88 | |
| 89 | impl ServingReservation { |
| 90 | /// The start-up log line a chip run reads. |
| 91 | pub fn log_line(&self) -> String { |
| 92 | let (b, y) = (&self.bounds, &self.bytes); |
| 93 | format!( |
| 94 | "GB10_SERVING_RESERVATION reserved bytes={} (attention pool {} + q/out {}x2 + table {}; matmul activation {} + result {}) \ |
| 95 | bounds: context<={} seqs<={} rows<={} k<={} n<={} logits_n<={} kernel_slots={}; \ |
| 96 | prepared {} matmul kernel calls in {} ms, then sealed; \ |
| 97 | calls past the bounds or unprepared kernels are refused TOO_LARGE; not covered: elementwise scratch, attention kernel", |
| 98 | y.total(), |
| 99 | y.attention_pool, |
| 100 | y.attention_q_out, |
| 101 | y.attention_table, |
| 102 | y.matmul_activation, |
| 103 | y.matmul_result, |
| 104 | b.max_context, |
| 105 | b.max_seqs, |
| 106 | b.max_rows, |
| 107 | b.max_k, |
| 108 | b.max_n, |
| 109 | b.max_n_one_row, |
| 110 | b.kernel_slots, |
| 111 | self.prepare_calls, |
| 112 | self.elapsed.as_millis(), |
| 113 | ) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | fn dim(what: &str, v: usize) -> Result<u32, String> { |
| 118 | match u32::try_from(v) { |
| 119 | Ok(x) if x > 0 => Ok(x), |
| 120 | _ => Err(format!("{what} = {v} is not a usable serving bound")), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// The distinct `(k, n)` weight shapes the forward pass multiplies, from the model config: |
| 125 | /// q (hidden, q_dim), k and v (hidden, kv_dim), o (q_dim, hidden), gate and up (hidden, |
| 126 | /// intermediate), down (intermediate, hidden), and the logits projection (hidden, vocab). |
| 127 | pub fn serving_matmul_shapes(config: &ModelConfig) -> Result<Vec<(u32, u32)>, String> { |
| 128 | let h = dim("hidden_dim", config.hidden_dim)?; |
| 129 | let q = dim("q width", config.num_heads * config.head_dim)?; |
| 130 | let kv = dim("kv width", config.num_kv_heads * config.head_dim)?; |
| 131 | let i = dim("intermediate_dim", config.intermediate_dim)?; |
| 132 | let v = dim("vocab_size", config.vocab_size)?; |
| 133 | let set: BTreeSet<(u32, u32)> = [(h, q), (h, kv), (q, h), (h, i), (i, h), (h, v)] |
| 134 | .into_iter() |
| 135 | .collect(); |
| 136 | Ok(set.into_iter().collect()) |
| 137 | } |
| 138 | |
| 139 | /// Bounds for `config` under `limits`. Errors name the offending number. |
| 140 | pub fn gb10_serving_bounds( |
| 141 | config: &ModelConfig, |
| 142 | limits: &ServingLimits, |
| 143 | ) -> Result<ServingBounds, String> { |
| 144 | let q_dim = config.num_heads * config.head_dim; |
| 145 | let kv_dim = config.num_kv_heads * config.head_dim; |
| 146 | // Widest input: o_proj reads q_dim, q/k/v/gate/up read hidden, down_proj reads intermediate. |
| 147 | let max_k = config.hidden_dim.max(q_dim).max(config.intermediate_dim); |
| 148 | // Widest output for a call of up to max_rows rows. The batched decode path projects the |
| 149 | // logits with every decode row (transformer_backend.rs, step 7: matmul_batch M = D), so the |
| 150 | // vocabulary is in the many-row bound as well as the one-row bound. |
| 151 | let max_n = q_dim |
| 152 | .max(kv_dim) |
| 153 | .max(config.hidden_dim) |
| 154 | .max(config.intermediate_dim) |
| 155 | .max(config.vocab_size); |
| 156 | let context = limits |
| 157 | .context_tokens |
| 158 | .min(GB10_ATTENTION_MAX_CONTEXT as usize); |
| 159 | let max_rows = dim( |
| 160 | "max rows (max_batch_size, prefill chunk)", |
| 161 | limits.max_batch_rows.max(limits.prefill_chunk_rows), |
| 162 | )?; |
| 163 | Ok(ServingBounds { |
| 164 | max_context: dim("declared context", context)?, |
| 165 | // omega_backend.rs paged_attention_batch runs one chip_paged_one call per sequence. |
| 166 | max_seqs: 1, |
| 167 | num_q_heads: dim("num_heads", config.num_heads)?, |
| 168 | num_kv_heads: dim("num_kv_heads", config.num_kv_heads)?, |
| 169 | head_dim: dim("head_dim", config.head_dim)?, |
| 170 | kv_block_size: dim("block_size", config.block_size)?, |
| 171 | max_rows, |
| 172 | max_k: dim("widest input dimension", max_k)?, |
| 173 | max_n: dim("widest output dimension", max_n)?, |
| 174 | max_n_one_row: dim("vocab_size", config.vocab_size)?, |
| 175 | kernel_slots: GB10_MATMUL_KERNEL_SLOTS, |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | /// The start-up sequence, with the GPU, the opt-in and the omega calls passed in. |
| 180 | /// |
| 181 | /// `Ok(None)`: it does not apply (not a GB10 build, not Qwen3, or the Qwen3 opt-in is off, in |
| 182 | /// which case the default refusal in `check_model` stops the model before any serving). |
| 183 | /// `Ok(Some(_))`: reserved, every (rows, shape) kernel prepared, sealed. `Err(_)`: omega refused |
| 184 | /// the reservation or a prepare (or a bound could not be formed); the caller must refuse to |
| 185 | /// serve. There is no on-demand fallback. The reservation is held for the life of the process |
| 186 | /// (omega ends it when it closes the device); this never releases it. |
| 187 | pub fn reserve_gb10_serving_with( |
| 188 | config: &ModelConfig, |
| 189 | limits: &ServingLimits, |
| 190 | gpu_native: bool, |
| 191 | qwen3_enabled: bool, |
| 192 | ops: &dyn ServingOps, |
| 193 | ) -> Result<Option<ServingReservation>, String> { |
| 194 | if !gpu_native || !config.qk_norm || omega_model_refusal_with(config, qwen3_enabled).is_some() { |
| 195 | return Ok(None); |
| 196 | } |
| 197 | let refuse = |why: String| { |
| 198 | format!( |
| 199 | "GB10_SERVING_RESERVATION refused for {:?}: {why}; refusing to serve (sovereign-core#277: \ |
| 200 | no on-demand fallback, because on-demand growth is the driver allocation that fails when MemFree is low)", |
| 201 | config.model_id |
| 202 | ) |
| 203 | }; |
| 204 | let started = Instant::now(); |
| 205 | let bounds = gb10_serving_bounds(config, limits).map_err(&refuse)?; |
| 206 | let shapes = serving_matmul_shapes(config).map_err(&refuse)?; |
| 207 | ops.reserve(&bounds).map_err(&refuse)?; |
| 208 | let mut prepare_calls = 0u32; |
| 209 | for m in 1..=bounds.max_rows { |
| 210 | for &(k, n) in &shapes { |
| 211 | ops.prepare(m, k, n) |
| 212 | .map_err(|e| refuse(format!("matmul kernel prepare m={m} k={k} n={n}: {e}")))?; |
| 213 | prepare_calls += 1; |
| 214 | } |
| 215 | } |
| 216 | ops.seal(); |
| 217 | Ok(Some(ServingReservation { |
| 218 | bounds, |
| 219 | bytes: bounds.bytes(), |
| 220 | prepare_calls, |
| 221 | elapsed: started.elapsed(), |
| 222 | })) |
| 223 | } |
| 224 | |
| 225 | /// The real calls: omega's `omega_gpu_reserve_serving`, `omega_gpu_matmul_prepare` and |
| 226 | /// `omega_gpu_serving_seal`, with omega's stage text added to a refusal. |
| 227 | pub struct OmegaServingOps; |
| 228 | |
| 229 | fn with_stage(e: aien_omega_gpu::OmegaGpuError) -> String { |
| 230 | let stage = aien_omega_gpu::last_error(); |
| 231 | if stage.is_empty() { |
| 232 | e.to_string() |
| 233 | } else { |
| 234 | format!("{e} (omega: {stage})") |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | impl ServingOps for OmegaServingOps { |
| 239 | fn reserve(&self, b: &ServingBounds) -> Result<(), String> { |
| 240 | aien_omega_gpu::reserve_serving(b).map_err(with_stage) |
| 241 | } |
| 242 | fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String> { |
| 243 | aien_omega_gpu::matmul_prepare(m, k, n).map_err(with_stage) |
| 244 | } |
| 245 | fn seal(&self) { |
| 246 | aien_omega_gpu::seal_serving(); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// Reads the serving log lines the daemon prints next to `GB10_SERVING_RESERVATION`: the |
| 251 | /// allocation counters once after warm-up, and the change since warm-up after every request. |
| 252 | /// A nonzero change is printed loudly, never hidden. |
| 253 | pub trait ServingProbe: Send + Sync { |
| 254 | /// Called once, after the declared warm-up and before the first request is accepted. |
| 255 | fn after_warm_up(&self) -> Option<String>; |
| 256 | /// Called after each served connection. |
| 257 | fn after_request(&self) -> Option<String>; |
| 258 | } |
| 259 | |
| 260 | /// [`ServingProbe`] over omega's allocation counters (`omega_gpu_session_alloc_stats`). |
| 261 | /// Counters are cumulative for the process, so overlapping requests cannot confuse the delta. |
| 262 | pub struct AllocProbe { |
| 263 | read: Box<dyn Fn() -> Option<aien_omega_gpu::AllocStats> + Send + Sync>, |
| 264 | baseline: std::sync::Mutex<Option<aien_omega_gpu::AllocStats>>, |
| 265 | } |
| 266 | |
| 267 | impl AllocProbe { |
| 268 | pub fn new(read: Box<dyn Fn() -> Option<aien_omega_gpu::AllocStats> + Send + Sync>) -> Self { |
| 269 | Self { |
| 270 | read, |
| 271 | baseline: std::sync::Mutex::new(None), |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | /// The probe on omega's real counters. |
| 276 | pub fn omega() -> Self { |
| 277 | Self::new(Box::new(aien_omega_gpu::alloc_stats)) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | impl ServingProbe for AllocProbe { |
| 282 | fn after_warm_up(&self) -> Option<String> { |
| 283 | let s = (self.read)()?; |
| 284 | *self.baseline.lock().ok()? = Some(s); |
| 285 | Some(format!( |
| 286 | "GB10_SERVING_ALLOC after_warmup allocs={} bytes={} failures={} frees={}", |
| 287 | s.allocs, s.alloc_bytes, s.alloc_failures, s.frees |
| 288 | )) |
| 289 | } |
| 290 | |
| 291 | fn after_request(&self) -> Option<String> { |
| 292 | let now = (self.read)()?; |
| 293 | let base = (*self.baseline.lock().ok()?)?; |
| 294 | let d = |a: u64, b: u64| a.saturating_sub(b); |
| 295 | let (allocs, bytes, failures, frees) = ( |
| 296 | d(now.allocs, base.allocs), |
| 297 | d(now.alloc_bytes, base.alloc_bytes), |
| 298 | d(now.alloc_failures, base.alloc_failures), |
| 299 | d(now.frees, base.frees), |
| 300 | ); |
| 301 | // Frees alone are not an allocation, but a free after warm-up means a buffer was replaced |
| 302 | // (or the daemon is tearing down), so it is flagged too, under its own name. |
| 303 | let flag = if allocs != 0 || failures != 0 { |
| 304 | " NONZERO: serving asked the driver for memory after warm-up" |
| 305 | } else if frees != 0 { |
| 306 | " FREES: driver memory released after warm-up (teardown, or a buffer was replaced)" |
| 307 | } else { |
| 308 | "" |
| 309 | }; |
| 310 | Some(format!( |
| 311 | "GB10_SERVING_ALLOC request allocs_since_warmup={allocs} bytes_since_warmup={bytes} failures_since_warmup={failures} frees_since_warmup={frees}{flag}" |
| 312 | )) |
| 313 | } |
| 314 | } |