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-heartbeat / src / pager.rs
| 1 | //! Expert pager (Expert Ribbon P2, sc#630/#632): turns the router's exact top-k for one layer into pinned, |
| 2 | //! resident GPU slots. Hits pin; misses read the expert from the checkpoint (bounded, digest-verified |
| 3 | //! [`ReadAdapter`]), split it into the chip layout and load it into a slot pair through a [`SlotBackend`]. |
| 4 | //! Misses of one layer are read and loaded in parallel (each on its own thread; the read adapter bounds how |
| 5 | //! many reads are in the kernel at once). |
| 6 | //! |
| 7 | //! Exactness: the experts returned are exactly the ones asked for, in the same order. A miss that cannot be |
| 8 | //! served (read error, digest mismatch, every slot pinned) is an error; nothing is substituted or skipped. |
| 9 | |
| 10 | use std::collections::HashMap; |
| 11 | use std::sync::{Arc, Condvar, Mutex}; |
| 12 | use std::time::{Duration, Instant}; |
| 13 | |
| 14 | use crate::layout::{ExpertLayout, ExpertParts, ExpertShape}; |
| 15 | use crate::manifest::Manifest; |
| 16 | use crate::reader::{ReadAdapter, ReadError}; |
| 17 | use crate::residency::{Acquire, ExpertId, Residency, ResidencyStats, SlotVersion}; |
| 18 | |
| 19 | #[cfg(feature = "ribbon-omega")] |
| 20 | mod pipeline; |
| 21 | |
| 22 | /// The GPU side of a slot pair. The real one wraps two omega_gpu_fp8_slots pools (gate|up and down); |
| 23 | /// tests use a host fake. Must be callable from several threads at once (one load per slot at a time). |
| 24 | pub trait SlotBackend: Send + Sync { |
| 25 | fn slots(&self) -> usize; |
| 26 | /// Load `parts` into slot pair `slot`, returning the published versions. Refused (error) if the slot is |
| 27 | /// still read by a launch: the residency manager never asks for that, so a refusal is a bug, fail closed. |
| 28 | fn load(&self, slot: u32, id: ExpertId, parts: &ExpertParts<'_>) |
| 29 | -> Result<SlotVersion, String>; |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug)] |
| 33 | pub enum PagerError { |
| 34 | Read { |
| 35 | id: ExpertId, |
| 36 | err: ReadError, |
| 37 | }, |
| 38 | Layout(String), |
| 39 | Backend { |
| 40 | id: ExpertId, |
| 41 | err: String, |
| 42 | }, |
| 43 | /// Every slot is pinned or being fetched: the capacity is too small for this request. |
| 44 | Exhausted { |
| 45 | id: ExpertId, |
| 46 | capacity: usize, |
| 47 | }, |
| 48 | UnknownExpert(ExpertId), |
| 49 | } |
| 50 | |
| 51 | impl std::fmt::Display for PagerError { |
| 52 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 53 | match self { |
| 54 | Self::Read { id, err } => write!(f, "expert {id:?}: read failed: {err}"), |
| 55 | Self::Layout(s) => write!(f, "expert layout: {s}"), |
| 56 | Self::Backend { id, err } => write!(f, "expert {id:?}: slot load failed: {err}"), |
| 57 | Self::Exhausted { id, capacity } => write!( |
| 58 | f, |
| 59 | "expert {id:?}: all {capacity} slots are pinned or loading (capacity too small for one request)" |
| 60 | ), |
| 61 | Self::UnknownExpert(id) => write!(f, "expert {id:?} is not in the manifest"), |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | impl std::error::Error for PagerError {} |
| 66 | |
| 67 | #[derive(Debug, Clone, Default)] |
| 68 | pub struct PagerStats { |
| 69 | pub requests: u64, |
| 70 | pub experts_hit: u64, |
| 71 | pub experts_missed: u64, |
| 72 | pub bytes_loaded: u64, |
| 73 | /// Wall time inside `ensure` spent on misses (read + verify + slot load), summed per call. |
| 74 | pub miss_wall_ns: u64, |
| 75 | /// Summed over miss threads: waiting for the verified read, and loading the slot pair. |
| 76 | pub read_wait_ns: u64, |
| 77 | pub slot_load_ns: u64, |
| 78 | } |
| 79 | |
| 80 | /// Slots pinned for one layer's launch, in the order the router gave the experts. |
| 81 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 82 | pub struct Pinned { |
| 83 | pub slots: Vec<u32>, |
| 84 | pub versions: Vec<SlotVersion>, |
| 85 | } |
| 86 | |
| 87 | pub struct ExpertPager { |
| 88 | manifest: Arc<Manifest>, |
| 89 | layouts: Vec<ExpertLayout>, |
| 90 | index_of: HashMap<ExpertId, usize>, |
| 91 | reader: ReadAdapter, |
| 92 | backend: Arc<dyn SlotBackend>, |
| 93 | res: Mutex<Residency>, |
| 94 | fetch_done: Condvar, |
| 95 | stats: Mutex<PagerStats>, |
| 96 | read_deadline: Duration, |
| 97 | } |
| 98 | |
| 99 | impl ExpertPager { |
| 100 | /// Validates every expert's layout against `shape` up front (a format mismatch fails here, not mid-run). |
| 101 | pub fn new( |
| 102 | manifest: Arc<Manifest>, |
| 103 | shape: ExpertShape, |
| 104 | reader: ReadAdapter, |
| 105 | backend: Arc<dyn SlotBackend>, |
| 106 | read_deadline: Duration, |
| 107 | ) -> Result<Self, PagerError> { |
| 108 | let layouts = manifest |
| 109 | .experts |
| 110 | .iter() |
| 111 | .map(|e| ExpertLayout::for_entry(e, shape)) |
| 112 | .collect::<Result<Vec<_>, _>>() |
| 113 | .map_err(|e| PagerError::Layout(e.to_string()))?; |
| 114 | let index_of = manifest |
| 115 | .experts |
| 116 | .iter() |
| 117 | .enumerate() |
| 118 | .map(|(i, e)| ((e.layer, e.expert), i)) |
| 119 | .collect(); |
| 120 | let slots = backend.slots(); |
| 121 | Ok(Self { |
| 122 | manifest, |
| 123 | layouts, |
| 124 | index_of, |
| 125 | reader, |
| 126 | backend, |
| 127 | res: Mutex::new(Residency::new(slots)), |
| 128 | fetch_done: Condvar::new(), |
| 129 | stats: Mutex::new(PagerStats::default()), |
| 130 | read_deadline, |
| 131 | }) |
| 132 | } |
| 133 | |
| 134 | pub fn manifest(&self) -> &Manifest { |
| 135 | &self.manifest |
| 136 | } |
| 137 | pub fn capacity(&self) -> usize { |
| 138 | self.res.lock().unwrap().capacity() |
| 139 | } |
| 140 | pub fn resident(&self) -> usize { |
| 141 | self.res.lock().unwrap().resident() |
| 142 | } |
| 143 | pub fn stats(&self) -> PagerStats { |
| 144 | self.stats.lock().unwrap().clone() |
| 145 | } |
| 146 | pub fn residency_stats(&self) -> ResidencyStats { |
| 147 | self.res.lock().unwrap().stats() |
| 148 | } |
| 149 | pub fn read_stats(&self) -> crate::reader::ReadStats { |
| 150 | self.reader.stats() |
| 151 | } |
| 152 | pub fn pinned(&self) -> u32 { |
| 153 | self.res.lock().unwrap().pinned() |
| 154 | } |
| 155 | |
| 156 | /// Pins exactly `experts` of `layer` (router order). On error nothing stays pinned. |
| 157 | pub fn ensure(&self, layer: u16, experts: &[u16]) -> Result<Pinned, PagerError> { |
| 158 | let wait_start = Instant::now(); |
| 159 | let mut out: Vec<Option<(u32, SlotVersion)>> = vec![None; experts.len()]; |
| 160 | let mut fetch: Vec<(usize, u32, ExpertId)> = Vec::new(); // (position, slot, id) |
| 161 | { |
| 162 | let mut r = self.res.lock().unwrap(); |
| 163 | for (pos, &ex) in experts.iter().enumerate() { |
| 164 | let id = (layer, ex); |
| 165 | if !self.index_of.contains_key(&id) { |
| 166 | self.undo(&mut r, &out, &fetch); |
| 167 | return Err(PagerError::UnknownExpert(id)); |
| 168 | } |
| 169 | loop { |
| 170 | match r.acquire(id) { |
| 171 | Acquire::Hit { slot, ver } => { |
| 172 | out[pos] = Some((slot, ver)); |
| 173 | break; |
| 174 | } |
| 175 | Acquire::Fetch { slot, .. } => { |
| 176 | fetch.push((pos, slot, id)); |
| 177 | break; |
| 178 | } |
| 179 | Acquire::Pending => { |
| 180 | let Some(left) = self.read_deadline.checked_sub(wait_start.elapsed()) |
| 181 | else { |
| 182 | self.undo(&mut r, &out, &fetch); |
| 183 | return Err(PagerError::Read { |
| 184 | id, |
| 185 | err: ReadError::Deadline, |
| 186 | }); |
| 187 | }; |
| 188 | r = self.fetch_done.wait_timeout(r, left).unwrap().0; |
| 189 | } |
| 190 | Acquire::Exhausted => { |
| 191 | let capacity = r.capacity(); |
| 192 | self.undo(&mut r, &out, &fetch); |
| 193 | return Err(PagerError::Exhausted { id, capacity }); |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | let hits = (experts.len() - fetch.len()) as u64; |
| 200 | let t0 = Instant::now(); |
| 201 | let results: Vec<Result<(SlotVersion, u64, u64, u64), PagerError>> = if fetch.is_empty() { |
| 202 | Vec::new() |
| 203 | } else { |
| 204 | std::thread::scope(|sc| { |
| 205 | let hs: Vec<_> = fetch |
| 206 | .iter() |
| 207 | .map(|&(_, slot, id)| sc.spawn(move || self.fetch_one(slot, id))) |
| 208 | .collect(); |
| 209 | hs.into_iter() |
| 210 | .map(|h| { |
| 211 | h.join().unwrap_or_else(|_| { |
| 212 | Err(PagerError::Layout("miss thread panicked".into())) |
| 213 | }) |
| 214 | }) |
| 215 | .collect() |
| 216 | }) |
| 217 | }; |
| 218 | let miss_wall = t0.elapsed().as_nanos() as u64; |
| 219 | let mut first_err = None; |
| 220 | { |
| 221 | let mut r = self.res.lock().unwrap(); |
| 222 | for (&(pos, slot, _), res) in fetch.iter().zip(&results) { |
| 223 | match res { |
| 224 | Ok((ver, ..)) => { |
| 225 | r.fetched(slot, *ver); |
| 226 | out[pos] = Some((slot, *ver)); |
| 227 | } |
| 228 | Err(_) => r.fetch_failed(slot), |
| 229 | } |
| 230 | } |
| 231 | for res in &results { |
| 232 | if let Err(e) = res { |
| 233 | first_err.get_or_insert_with(|| format!("{e}")); |
| 234 | } |
| 235 | } |
| 236 | if first_err.is_some() { |
| 237 | for (slot, _) in out.iter().flatten() { |
| 238 | r.release(*slot); |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | self.fetch_done.notify_all(); |
| 243 | let mut s = self.stats.lock().unwrap(); |
| 244 | s.requests += 1; |
| 245 | s.experts_hit += hits; |
| 246 | s.experts_missed += fetch.len() as u64; |
| 247 | s.miss_wall_ns += miss_wall; |
| 248 | for (_, rw, sl, b) in results.iter().flatten() { |
| 249 | s.read_wait_ns += rw; |
| 250 | s.slot_load_ns += sl; |
| 251 | s.bytes_loaded += b; |
| 252 | } |
| 253 | drop(s); |
| 254 | if let Some(e) = results.into_iter().find_map(|r| r.err()) { |
| 255 | return Err(e); |
| 256 | } |
| 257 | let (slots, versions) = out |
| 258 | .into_iter() |
| 259 | .map(|o| o.expect("every position filled")) |
| 260 | .unzip(); |
| 261 | Ok(Pinned { slots, versions }) |
| 262 | } |
| 263 | |
| 264 | /// Drops the pins of a finished launch. |
| 265 | pub fn release(&self, p: &Pinned) { |
| 266 | let mut r = self.res.lock().unwrap(); |
| 267 | for &s in &p.slots { |
| 268 | r.release(s); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | fn undo( |
| 273 | &self, |
| 274 | r: &mut Residency, |
| 275 | out: &[Option<(u32, SlotVersion)>], |
| 276 | fetch: &[(usize, u32, ExpertId)], |
| 277 | ) { |
| 278 | for (slot, _) in out.iter().flatten() { |
| 279 | r.release(*slot); |
| 280 | } |
| 281 | for &(_, slot, _) in fetch { |
| 282 | r.fetch_failed(slot); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// Read + verify + split + slot load. Returns (version, read wait ns, slot load ns, bytes). |
| 287 | fn fetch_one( |
| 288 | &self, |
| 289 | slot: u32, |
| 290 | id: ExpertId, |
| 291 | ) -> Result<(SlotVersion, u64, u64, u64), PagerError> { |
| 292 | let idx = self.index_of[&id]; |
| 293 | let t0 = Instant::now(); |
| 294 | let v = self |
| 295 | .reader |
| 296 | .submit_wait(idx, self.read_deadline) |
| 297 | .and_then(|t| t.wait(self.read_deadline)) |
| 298 | .map_err(|err| PagerError::Read { id, err })?; |
| 299 | let rw = t0.elapsed().as_nanos() as u64; |
| 300 | let t1 = Instant::now(); |
| 301 | let payload = v.payload(); |
| 302 | let parts = self.layouts[idx] |
| 303 | .parts(&payload) |
| 304 | .map_err(|e| PagerError::Layout(e.to_string()))?; |
| 305 | let bytes = (parts.gate_up_w.len() |
| 306 | + parts.down_w.len() |
| 307 | + 2 * (parts.gate_up_s.len() + parts.down_s.len())) as u64; |
| 308 | let ver = self |
| 309 | .backend |
| 310 | .load(slot, id, &parts) |
| 311 | .map_err(|err| PagerError::Backend { id, err })?; |
| 312 | Ok((ver, rw, t1.elapsed().as_nanos() as u64, bytes)) |
| 313 | } |
| 314 | } |