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-heartbeat/src/residency.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-heartbeat / src / residency.rs` 405 lines ยท 12968 bytes Raw Blame History 1 //! Bounded expert residency (Expert Ribbon P2, sc#630): which (layer, expert) lives in which GPU slot, 2 //! who is using it, and which slot to reuse next. Host-only; the GPU side is behind 3 //! [`crate::pager::SlotBackend`]. 4 //! 5 //! Slot life cycle (one slot = one gate|up slot + one down slot on the device): 6 //! ```text 7 //! FREE --acquire(miss)--> FETCHING(id) --fetched(ver)--> READY(id, ver) pinned by the requester 8 //! FETCHING(id) --fetch_failed--> FREE (nothing published) 9 //! READY, pins > 0 = IN USE (never chosen as a victim) 10 //! READY, pins == 0 = EVICTABLE (least recently used one is reused on a miss) 11 //! ``` 12 //! Exactly the router's experts run: a miss waits for that expert or fails; nothing is substituted. 13 //! When every slot is pinned or fetching the request fails with [`Acquire::Exhausted`] (backpressure, explicit). 14 15 use std::collections::HashMap; 16 17 /// `(layer, expert)`. 18 pub type ExpertId = (u16, u16); 19 20 /// Device versions of one slot pair (omega_gpu_fp8_slots versions of the gate|up and the down slot). 21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] 22 pub struct SlotVersion { 23 pub gate_up: u64, 24 pub down: u64, 25 } 26 27 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 28 enum State { 29 Free, 30 Fetching(ExpertId), 31 Ready(ExpertId, SlotVersion), 32 } 33 34 #[derive(Debug, Clone, Copy)] 35 struct Slot { 36 state: State, 37 pins: u32, 38 last_use: u64, 39 } 40 41 #[derive(Debug, Clone, PartialEq, Eq)] 42 pub enum Acquire { 43 /// Resident: pinned for the caller. 44 Hit { slot: u32, ver: SlotVersion }, 45 /// Not resident: `slot` is reserved (FETCHING) for the caller, who must call `fetched` or `fetch_failed`. 46 Fetch { 47 slot: u32, 48 evicted: Option, 49 }, 50 /// Another request is fetching this expert right now. 51 Pending, 52 /// Every slot is pinned or fetching. 53 Exhausted, 54 } 55 56 #[derive(Debug, Clone, Default, PartialEq, Eq)] 57 pub struct ResidencyStats { 58 pub hits: u64, 59 pub misses: u64, 60 pub evictions: u64, 61 pub fetch_failures: u64, 62 pub exhausted: u64, 63 pub pinned_high: u32, 64 } 65 66 #[derive(Debug)] 67 pub struct Residency { 68 slots: Vec, 69 map: HashMap, 70 tick: u64, 71 pinned: u32, 72 stats: ResidencyStats, 73 } 74 75 impl Residency { 76 pub fn new(slots: usize) -> Self { 77 assert!(slots > 0 && slots <= u32::MAX as usize); 78 Self { 79 slots: vec![ 80 Slot { 81 state: State::Free, 82 pins: 0, 83 last_use: 0, 84 }; 85 slots 86 ], 87 map: HashMap::new(), 88 tick: 0, 89 pinned: 0, 90 stats: ResidencyStats::default(), 91 } 92 } 93 94 pub fn capacity(&self) -> usize { 95 self.slots.len() 96 } 97 98 pub fn stats(&self) -> ResidencyStats { 99 self.stats.clone() 100 } 101 102 /// Experts currently READY (resident). 103 pub fn resident(&self) -> usize { 104 self.slots 105 .iter() 106 .filter(|s| matches!(s.state, State::Ready(..))) 107 .count() 108 } 109 110 /// Slot and version of `id` if READY (no pin taken). 111 pub fn lookup(&self, id: ExpertId) -> Option<(u32, SlotVersion)> { 112 let s = *self.map.get(&id)?; 113 match self.slots[s as usize].state { 114 State::Ready(_, v) => Some((s, v)), 115 _ => None, 116 } 117 } 118 119 pub fn pins(&self, slot: u32) -> u32 { 120 self.slots[slot as usize].pins 121 } 122 123 fn pin(&mut self, slot: u32) { 124 self.tick += 1; 125 let s = &mut self.slots[slot as usize]; 126 s.pins += 1; 127 s.last_use = self.tick; 128 self.pinned += 1; 129 self.stats.pinned_high = self.stats.pinned_high.max(self.pinned); 130 } 131 132 pub fn acquire(&mut self, id: ExpertId) -> Acquire { 133 if let Some(&slot) = self.map.get(&id) { 134 return match self.slots[slot as usize].state { 135 State::Ready(_, ver) => { 136 self.pin(slot); 137 self.stats.hits += 1; 138 Acquire::Hit { slot, ver } 139 } 140 State::Fetching(_) => Acquire::Pending, 141 State::Free => unreachable!("map points at a free slot"), 142 }; 143 } 144 // Victim: a free slot first, else the least recently used unpinned READY slot. 145 let victim = self 146 .slots 147 .iter() 148 .position(|s| s.state == State::Free) 149 .or_else(|| { 150 self.slots 151 .iter() 152 .enumerate() 153 .filter(|(_, s)| s.pins == 0 && matches!(s.state, State::Ready(..))) 154 .min_by_key(|(_, s)| s.last_use) 155 .map(|(i, _)| i) 156 }); 157 let Some(v) = victim else { 158 self.stats.exhausted += 1; 159 return Acquire::Exhausted; 160 }; 161 let evicted = match self.slots[v].state { 162 State::Ready(old, _) => { 163 self.map.remove(&old); 164 self.stats.evictions += 1; 165 Some(old) 166 } 167 _ => None, 168 }; 169 self.slots[v].state = State::Fetching(id); 170 self.map.insert(id, v as u32); 171 self.stats.misses += 1; 172 Acquire::Fetch { 173 slot: v as u32, 174 evicted, 175 } 176 } 177 178 /// The fetch into `slot` completed and was published at `ver`: READY, pinned for the requester. 179 pub fn fetched(&mut self, slot: u32, ver: SlotVersion) { 180 let State::Fetching(id) = self.slots[slot as usize].state else { 181 panic!("fetched on a slot that is not fetching"); 182 }; 183 self.slots[slot as usize].state = State::Ready(id, ver); 184 self.pin(slot); 185 } 186 187 /// The fetch into `slot` failed: the slot is FREE, the expert is not resident. 188 pub fn fetch_failed(&mut self, slot: u32) { 189 let State::Fetching(id) = self.slots[slot as usize].state else { 190 panic!("fetch_failed on a slot that is not fetching"); 191 }; 192 self.map.remove(&id); 193 self.slots[slot as usize].state = State::Free; 194 self.stats.fetch_failures += 1; 195 } 196 197 pub fn release(&mut self, slot: u32) { 198 let s = &mut self.slots[slot as usize]; 199 assert!(s.pins > 0, "release without a pin"); 200 s.pins -= 1; 201 self.pinned -= 1; 202 } 203 204 /// Total pins outstanding (0 between requests). 205 pub fn pinned(&self) -> u32 { 206 self.pinned 207 } 208 } 209 210 /// Memory ledger for admitting expert slots (sc#630): everything else is budgeted first, slots get what is 211 /// left, and a request for more is refused rather than assumed. 212 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 213 pub struct MemoryBudget { 214 /// MemAvailable at load time (bytes). 215 pub available: u64, 216 /// Kept free for the OS, the driver and other processes. 217 pub headroom: u64, 218 /// Resident non-expert weights (attention, router, lm_head, host embedding). 219 pub non_expert: u64, 220 /// KV cache at the configured max context. 221 pub kv: u64, 222 /// Launch scratch, staging buffers and other transients. 223 pub scratch: u64, 224 } 225 226 impl MemoryBudget { 227 pub fn for_slots(&self) -> u64 { 228 self.available 229 .saturating_sub(self.headroom) 230 .saturating_sub(self.non_expert) 231 .saturating_sub(self.kv) 232 .saturating_sub(self.scratch) 233 } 234 235 /// Admits `want` slots of `slot_bytes` each, or refuses with the ledger. 236 pub fn admit(&self, want: usize, slot_bytes: u64) -> Result<(), String> { 237 let need = want as u64 * slot_bytes; 238 if need > self.for_slots() { 239 return Err(format!( 240 "expert slots need {need} bytes ({want} x {slot_bytes}) but only {} are left: available {} - headroom {} - non-expert {} - kv {} - scratch {}", 241 self.for_slots(), 242 self.available, 243 self.headroom, 244 self.non_expert, 245 self.kv, 246 self.scratch 247 )); 248 } 249 Ok(()) 250 } 251 } 252 253 /// `MemAvailable` from /proc/meminfo, bytes. 254 pub fn mem_available() -> Option { 255 let s = std::fs::read_to_string("/proc/meminfo").ok()?; 256 let l = s.lines().find(|l| l.starts_with("MemAvailable:"))?; 257 let kb: u64 = l.split_whitespace().nth(1)?.parse().ok()?; 258 Some(kb * 1024) 259 } 260 261 #[cfg(test)] 262 mod tests { 263 use super::*; 264 265 fn v(n: u64) -> SlotVersion { 266 SlotVersion { 267 gate_up: n, 268 down: n + 1000, 269 } 270 } 271 272 fn load(r: &mut Residency, id: ExpertId, n: u64) -> u32 { 273 match r.acquire(id) { 274 Acquire::Fetch { slot, .. } => { 275 r.fetched(slot, v(n)); 276 slot 277 } 278 other => panic!("{other:?}"), 279 } 280 } 281 282 #[test] 283 fn miss_then_hit_and_release() { 284 let mut r = Residency::new(2); 285 let s = load(&mut r, (0, 5), 1); 286 assert_eq!(r.pins(s), 1); 287 r.release(s); 288 assert_eq!(r.acquire((0, 5)), Acquire::Hit { slot: s, ver: v(1) }); 289 r.release(s); 290 assert_eq!(r.stats().hits, 1); 291 assert_eq!(r.stats().misses, 1); 292 assert_eq!(r.pinned(), 0); 293 } 294 295 #[test] 296 fn lru_eviction_order_and_layer_crossing_identities() { 297 let mut r = Residency::new(3); 298 for (i, id) in [(0, 1), (1, 1), (2, 1)].into_iter().enumerate() { 299 let s = load(&mut r, id, i as u64 + 1); 300 r.release(s); 301 } 302 // touch (0,1) so (1,1) is the least recent 303 let Acquire::Hit { slot, .. } = r.acquire((0, 1)) else { 304 panic!() 305 }; 306 r.release(slot); 307 match r.acquire((3, 1)) { 308 Acquire::Fetch { evicted, slot } => { 309 assert_eq!( 310 evicted, 311 Some((1, 1)), 312 "same expert number, other layer: distinct ids" 313 ); 314 r.fetched(slot, v(9)); 315 r.release(slot); 316 } 317 o => panic!("{o:?}"), 318 } 319 assert!(r.lookup((1, 1)).is_none()); 320 assert!(r.lookup((0, 1)).is_some() && r.lookup((2, 1)).is_some()); 321 assert_eq!(r.stats().evictions, 1); 322 } 323 324 #[test] 325 fn pinned_slots_are_never_evicted_and_exhaustion_is_explicit() { 326 let mut r = Residency::new(2); 327 let a = load(&mut r, (0, 0), 1); 328 let b = load(&mut r, (0, 1), 2); 329 assert_eq!(r.acquire((0, 2)), Acquire::Exhausted); 330 assert_eq!(r.stats().exhausted, 1); 331 r.release(b); 332 match r.acquire((0, 2)) { 333 Acquire::Fetch { slot, evicted } => { 334 assert_eq!((slot, evicted), (b, Some((0, 1)))); 335 r.fetched(slot, v(3)); 336 r.release(slot); 337 } 338 o => panic!("{o:?}"), 339 } 340 assert_eq!(r.lookup((0, 0)).map(|x| x.0), Some(a), "pinned slot kept"); 341 r.release(a); 342 } 343 344 #[test] 345 fn simultaneous_readers_share_a_slot() { 346 let mut r = Residency::new(1); 347 let s = load(&mut r, (4, 4), 1); 348 assert!(matches!(r.acquire((4, 4)), Acquire::Hit { .. })); 349 assert_eq!(r.pins(s), 2); 350 assert_eq!(r.acquire((4, 5)), Acquire::Exhausted); 351 r.release(s); 352 assert_eq!( 353 r.acquire((4, 5)), 354 Acquire::Exhausted, 355 "one reader still holds it" 356 ); 357 r.release(s); 358 assert!(matches!(r.acquire((4, 5)), Acquire::Fetch { .. })); 359 } 360 361 #[test] 362 fn fetching_is_pending_for_others_and_failure_recovers() { 363 let mut r = Residency::new(2); 364 let Acquire::Fetch { slot, .. } = r.acquire((1, 2)) else { 365 panic!() 366 }; 367 assert_eq!(r.acquire((1, 2)), Acquire::Pending); 368 r.fetch_failed(slot); 369 assert!(r.lookup((1, 2)).is_none()); 370 assert_eq!(r.stats().fetch_failures, 1); 371 let s2 = load(&mut r, (1, 2), 7); 372 assert_eq!(r.lookup((1, 2)), Some((s2, v(7)))); 373 r.release(s2); 374 } 375 376 #[test] 377 fn aba_reuse_gets_new_versions() { 378 // The same slot holds (0,0), then (0,1), then (0,0) again: the backend version differs each time, 379 // so a stale (slot, version) handle from the first load can never match the third. 380 let mut r = Residency::new(1); 381 let s = load(&mut r, (0, 0), 1); 382 r.release(s); 383 let s1 = load(&mut r, (0, 1), 2); 384 r.release(s1); 385 let s2 = load(&mut r, (0, 0), 3); 386 assert_eq!((s, s1, s2), (0, 0, 0)); 387 assert_eq!(r.lookup((0, 0)), Some((0, v(3)))); 388 r.release(s2); 389 } 390 391 #[test] 392 fn budget_admits_and_refuses() { 393 let b = MemoryBudget { 394 available: 100, 395 headroom: 10, 396 non_expert: 20, 397 kv: 30, 398 scratch: 5, 399 }; 400 assert_eq!(b.for_slots(), 35); 401 assert!(b.admit(7, 5).is_ok()); 402 let e = b.admit(8, 5).unwrap_err(); 403 assert!(e.contains("need 40"), "{e}"); 404 } 405 }