Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-dual-observation/src/lib.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-dual-observation / src / lib.rs` 394 lines · 15775 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! DUAL observation: a read-only macroscopic snapshot of the serve path 17 //! (ARCH-0031 DUAL-3a instrumentation). 18 //! 19 //! [`ServeObservationSnapshot::capture`] copies existing exact counters from 20 //! the scheduler, the KV manager and (when the caller has them) the last 21 //! `StepMetrics` and `ScheduledBatch` into one immutable struct, and derives 22 //! normalized densities from them. [`ObservationDelta::between`] subtracts two 23 //! snapshots to give arrival, completion and preemption counts over the 24 //! interval. 25 //! 26 //! Rules this crate keeps: 27 //! 28 //! - Every field documents the counter it is copied from. There is no second 29 //! ledger: nothing here is incremented, remembered between calls or 30 //! estimated. A snapshot is a pure function of the counters at the instant 31 //! `capture` ran. 32 //! - Every quotient is a [`Density`] with its exact numerator and denominator; 33 //! `Density::value` is `None` when the denominator is zero. No field is 34 //! interpolated or guessed. 35 //! - This crate reads through `&AienScheduler` and `&AienKvManager` only. It 36 //! cannot change a scheduling, admission, preemption or KV decision, and no 37 //! field of a snapshot is an authority input anywhere (ADR 0031 §6). 38 //! 39 //! The scheduler's internal step counter is private; the generation here is 40 //! `SchedulerMetrics::total_steps`, which counts completed steps that executed 41 //! a batch. Two snapshots with equal `generation` were taken without a step 42 //! completing between them. 43 44 use aien_abi_core::{ScheduledBatch, StepMetrics}; 45 use aien_kv_cache::{AienKvManager, KvMetrics}; 46 use aien_scheduler::AienScheduler; 47 use serde::{Deserialize, Serialize}; 48 49 /// An exact ratio kept as its two integers. `value()` is the normalized 50 /// density `numerator / denominator`, or `None` when the denominator is zero 51 /// (the zero-denominator rule for every density in this crate). 52 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 53 pub struct Density { 54 pub numerator: usize, 55 pub denominator: usize, 56 } 57 58 impl Density { 59 pub fn new(numerator: usize, denominator: usize) -> Self { 60 Self { 61 numerator, 62 denominator, 63 } 64 } 65 66 /// `numerator / denominator`, `None` when `denominator == 0`. 67 pub fn value(&self) -> Option { 68 if self.denominator == 0 { 69 None 70 } else { 71 Some(self.numerator as f64 / self.denominator as f64) 72 } 73 } 74 } 75 76 /// Copy of the last `StepMetrics` the caller received from 77 /// `AienScheduler::step`. `step_latency_us` is left out on purpose: it is a 78 /// timing, not a count, and DUAL observation records counts. 79 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 80 pub struct StepReading { 81 /// `StepMetrics::prefill_tokens_processed`. 82 pub prefill_tokens_processed: usize, 83 /// `StepMetrics::decode_tokens_emitted`. 84 pub decode_tokens_emitted: usize, 85 /// `StepMetrics::active_kv_blocks` (`AienKvManager::allocated_block_count` 86 /// after the step, as the scheduler fills it). 87 pub active_kv_blocks: usize, 88 } 89 90 impl From<&StepMetrics> for StepReading { 91 fn from(m: &StepMetrics) -> Self { 92 Self { 93 prefill_tokens_processed: m.prefill_tokens_processed, 94 decode_tokens_emitted: m.decode_tokens_emitted, 95 active_kv_blocks: m.active_kv_blocks, 96 } 97 } 98 } 99 100 /// Sizes of the last `ScheduledBatch` the caller saw. 101 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 102 pub struct BatchReading { 103 /// `ScheduledBatch::step_id`. 104 pub step_id: u64, 105 /// `ScheduledBatch::prefill_requests.len()`. 106 pub prefill_requests: usize, 107 /// `ScheduledBatch::decode_requests.len()`. 108 pub decode_requests: usize, 109 /// Sum of `prompt_tokens.len()` over `prefill_requests` plus one per 110 /// decode request: the quantity the scheduler compares against 111 /// `max_batch_tokens`. 112 pub batch_tokens: usize, 113 } 114 115 impl From<&ScheduledBatch> for BatchReading { 116 fn from(b: &ScheduledBatch) -> Self { 117 Self { 118 step_id: b.step_id, 119 prefill_requests: b.prefill_requests.len(), 120 decode_requests: b.decode_requests.len(), 121 batch_tokens: b 122 .prefill_requests 123 .iter() 124 .map(|r| r.prompt_tokens.len()) 125 .sum::() 126 + b.decode_requests.len(), 127 } 128 } 129 } 130 131 /// One read-only macroscopic snapshot of the serve path. 132 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 133 pub struct ServeObservationSnapshot { 134 /// `SchedulerMetrics::total_steps`: completed steps that executed a batch. 135 pub generation: u64, 136 137 // Scheduler queues and arena. 138 /// `AienScheduler::waiting_count()`. 139 pub waiting: usize, 140 /// `AienScheduler::preempted_count()`. 141 pub preempted: usize, 142 /// `AienScheduler::running_count()`. 143 pub running: usize, 144 /// `SequenceArena::active_count()` via `AienScheduler::arena()`. 145 pub arena_active: usize, 146 147 // Scheduler lifetime counters (`SchedulerMetrics`). 148 /// `SchedulerMetrics::admitted_requests` (counts `submit_request` and 149 /// `submit_work`; a `fork_sequence` child is not counted here). 150 pub admitted_requests: u64, 151 /// `SchedulerMetrics::finished_requests`. 152 pub finished_requests: u64, 153 /// `SchedulerMetrics::preempted_requests` (lifetime count of preemption 154 /// events, not the current queue length). 155 pub preempted_requests: u64, 156 /// `SchedulerMetrics::total_prefill_tokens`. 157 pub total_prefill_tokens: u64, 158 /// `SchedulerMetrics::total_decode_tokens`. 159 pub total_decode_tokens: u64, 160 /// `SchedulerMetrics::chunked_prefill_steps`. 161 pub chunked_prefill_steps: u64, 162 163 // Scheduler limits (`SchedulerConfig`). 164 /// `SchedulerConfig::max_batch_size`. 165 pub max_batch_size: usize, 166 /// `SchedulerConfig::max_batch_tokens`. 167 pub max_batch_tokens: usize, 168 /// `SchedulerConfig::watermark_blocks`. 169 pub watermark_blocks: usize, 170 171 // KV pool (`AienKvManager`). 172 /// `AienKvManager::total_block_count()`. 173 pub kv_total_blocks: usize, 174 /// `AienKvManager::available_blocks()` (free-list length). 175 pub kv_free_blocks: usize, 176 /// `AienKvManager::allocated_block_count()` (`total - free`). 177 pub kv_allocated_blocks: usize, 178 /// `AienKvManager::active_sequence_count()` (block tables held). 179 pub kv_active_tables: usize, 180 /// `KvMetrics::physical_pages` (blocks with `ref_count > 0`). 181 pub kv_physical_pages: usize, 182 /// `KvMetrics::logical_pages` (sum of table lengths). 183 pub kv_logical_pages: usize, 184 /// `KvMetrics::shared_pages` (blocks with `ref_count > 1`). 185 pub kv_shared_pages: usize, 186 /// `KvMetrics::private_pages` (blocks with `ref_count == 1`). 187 pub kv_private_pages: usize, 188 /// `KvMetrics::cow_faults`. 189 pub kv_cow_faults: usize, 190 /// `KvMetrics::used_blocks` (equals `physical_pages` by its definition). 191 pub kv_used_blocks: usize, 192 /// `AienKvManager::available_blocks() < SchedulerConfig::watermark_blocks`, 193 /// the pool half of the scheduler's preemption predicate (the other half, 194 /// "something is running", is `running > 0`). 195 pub kv_below_watermark: bool, 196 197 // Last step and batch, when the caller had them. 198 pub last_step: Option, 199 pub last_batch: Option, 200 201 // Normalized densities (used / capacity). Denominator zero gives None. 202 /// `kv_allocated_blocks / kv_total_blocks`. 203 pub kv_block_density: Density, 204 /// `(kv_logical_pages - kv_physical_pages) / kv_logical_pages`: the share 205 /// of logical pages served by sharing. `None` when no table holds a page. 206 pub kv_sharing_density: Density, 207 /// `running / max_batch_size`. 208 pub running_slot_density: Density, 209 /// `(prefill_requests + decode_requests) / max_batch_size` of the last 210 /// batch; numerator 0 when no batch was given. 211 pub batch_slot_density: Density, 212 /// `batch_tokens / max_batch_tokens` of the last batch; numerator 0 when 213 /// no batch was given. 214 pub batch_token_density: Density, 215 } 216 217 impl ServeObservationSnapshot { 218 /// Copies the counters. `kv` must be the manager the scheduler was built 219 /// with; the caller holds the read guard so both reads see one instant. 220 pub fn capture( 221 scheduler: &AienScheduler, 222 kv: &AienKvManager, 223 last_step: Option<&StepMetrics>, 224 last_batch: Option<&ScheduledBatch>, 225 ) -> Self { 226 let m = scheduler.metrics(); 227 let cfg = scheduler.config(); 228 let km: KvMetrics = kv.metrics(); 229 230 let kv_total_blocks = kv.total_block_count(); 231 let kv_free_blocks = kv.available_blocks(); 232 let kv_allocated_blocks = kv.allocated_block_count(); 233 let running = scheduler.running_count(); 234 let last_step = last_step.map(StepReading::from); 235 let last_batch = last_batch.map(BatchReading::from); 236 let (batch_slots, batch_tokens) = match &last_batch { 237 Some(b) => (b.prefill_requests + b.decode_requests, b.batch_tokens), 238 None => (0, 0), 239 }; 240 241 Self { 242 generation: m.total_steps, 243 waiting: scheduler.waiting_count(), 244 preempted: scheduler.preempted_count(), 245 running, 246 arena_active: scheduler.arena().active_count(), 247 admitted_requests: m.admitted_requests, 248 finished_requests: m.finished_requests, 249 preempted_requests: m.preempted_requests, 250 total_prefill_tokens: m.total_prefill_tokens, 251 total_decode_tokens: m.total_decode_tokens, 252 chunked_prefill_steps: m.chunked_prefill_steps, 253 max_batch_size: cfg.max_batch_size, 254 max_batch_tokens: cfg.max_batch_tokens, 255 watermark_blocks: cfg.watermark_blocks, 256 kv_total_blocks, 257 kv_free_blocks, 258 kv_allocated_blocks, 259 kv_active_tables: kv.active_sequence_count(), 260 kv_physical_pages: km.physical_pages, 261 kv_logical_pages: km.logical_pages, 262 kv_shared_pages: km.shared_pages, 263 kv_private_pages: km.private_pages, 264 kv_cow_faults: km.cow_faults, 265 kv_used_blocks: km.used_blocks, 266 kv_below_watermark: kv_free_blocks < cfg.watermark_blocks, 267 last_step, 268 last_batch, 269 kv_block_density: Density::new(kv_allocated_blocks, kv_total_blocks), 270 kv_sharing_density: Density::new( 271 km.logical_pages.saturating_sub(km.physical_pages), 272 km.logical_pages, 273 ), 274 running_slot_density: Density::new(running, cfg.max_batch_size), 275 batch_slot_density: Density::new(batch_slots, cfg.max_batch_size), 276 batch_token_density: Density::new(batch_tokens, cfg.max_batch_tokens), 277 } 278 } 279 } 280 281 /// Why two snapshots could not be subtracted. 282 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 283 pub enum DeltaError { 284 /// `later.generation < earlier.generation`: the order is reversed or the 285 /// snapshots come from different schedulers. 286 GenerationWentBackwards { earlier: u64, later: u64 }, 287 /// A lifetime counter decreased, which the scheduler never does; the 288 /// snapshots are not from one scheduler. 289 CounterWentBackwards { 290 counter: &'static str, 291 earlier: u64, 292 later: u64, 293 }, 294 /// The pool size differs; the snapshots are not from one KV manager. 295 PoolSizeChanged { earlier: usize, later: usize }, 296 } 297 298 /// Exact differences between two snapshots of the same scheduler. 299 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 300 pub struct ObservationDelta { 301 /// `later.generation - earlier.generation`: completed steps in between. 302 pub steps: u64, 303 /// `admitted_requests` difference: requests that arrived (were submitted). 304 pub arrivals: u64, 305 /// `finished_requests` difference. 306 pub completions: u64, 307 /// `preempted_requests` difference: preemption events. 308 pub preemptions: u64, 309 /// `total_prefill_tokens` difference. 310 pub prefill_tokens: u64, 311 /// `total_decode_tokens` difference. 312 pub decode_tokens: u64, 313 /// `later.kv_allocated_blocks - earlier.kv_allocated_blocks`, signed. 314 pub kv_allocated_change: i64, 315 /// `later.running - earlier.running`, signed. 316 pub running_change: i64, 317 /// `later.waiting - earlier.waiting`, signed. 318 pub waiting_change: i64, 319 } 320 321 impl ObservationDelta { 322 /// `later - earlier`. Refuses reversed order and snapshots that cannot 323 /// come from one scheduler and one pool. 324 pub fn between( 325 earlier: &ServeObservationSnapshot, 326 later: &ServeObservationSnapshot, 327 ) -> Result { 328 if later.generation < earlier.generation { 329 return Err(DeltaError::GenerationWentBackwards { 330 earlier: earlier.generation, 331 later: later.generation, 332 }); 333 } 334 if later.kv_total_blocks != earlier.kv_total_blocks { 335 return Err(DeltaError::PoolSizeChanged { 336 earlier: earlier.kv_total_blocks, 337 later: later.kv_total_blocks, 338 }); 339 } 340 let diff = |counter: &'static str, a: u64, b: u64| -> Result { 341 b.checked_sub(a).ok_or(DeltaError::CounterWentBackwards { 342 counter, 343 earlier: a, 344 later: b, 345 }) 346 }; 347 Ok(Self { 348 steps: later.generation - earlier.generation, 349 arrivals: diff( 350 "admitted_requests", 351 earlier.admitted_requests, 352 later.admitted_requests, 353 )?, 354 completions: diff( 355 "finished_requests", 356 earlier.finished_requests, 357 later.finished_requests, 358 )?, 359 preemptions: diff( 360 "preempted_requests", 361 earlier.preempted_requests, 362 later.preempted_requests, 363 )?, 364 prefill_tokens: diff( 365 "total_prefill_tokens", 366 earlier.total_prefill_tokens, 367 later.total_prefill_tokens, 368 )?, 369 decode_tokens: diff( 370 "total_decode_tokens", 371 earlier.total_decode_tokens, 372 later.total_decode_tokens, 373 )?, 374 kv_allocated_change: later.kv_allocated_blocks as i64 375 - earlier.kv_allocated_blocks as i64, 376 running_change: later.running as i64 - earlier.running as i64, 377 waiting_change: later.waiting as i64 - earlier.waiting as i64, 378 }) 379 } 380 } 381 382 #[cfg(test)] 383 mod tests { 384 use super::*; 385 386 #[test] 387 fn density_zero_denominator_is_none() { 388 assert_eq!(Density::new(0, 0).value(), None); 389 assert_eq!(Density::new(5, 0).value(), None); 390 assert_eq!(Density::new(0, 4).value(), Some(0.0)); 391 assert_eq!(Density::new(2, 4).value(), Some(0.5)); 392 assert_eq!(Density::new(4, 4).value(), Some(1.0)); 393 } 394 }