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 / stream.rs
| 1 | //! The streamer: a fixed pool of workers that read expert spans with |
| 2 | //! O_DIRECT `pread` into ring slots in layer order, verify, then publish. |
| 3 | //! |
| 4 | //! Schedule item `i` always lands in slot `i % slots`, and slot `s` is owned |
| 5 | //! by worker `s % workers`, so each slot has exactly one writer and slots are |
| 6 | //! refilled in schedule order. |
| 7 | |
| 8 | use std::collections::HashSet; |
| 9 | use std::fs::{File, OpenOptions}; |
| 10 | use std::os::unix::fs::{FileExt, OpenOptionsExt}; |
| 11 | use std::path::PathBuf; |
| 12 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | use crate::aligned::{round_down, round_up}; |
| 16 | use crate::error::HeartbeatError; |
| 17 | use crate::manifest::{ExpertEntry, Manifest}; |
| 18 | use crate::ring::Ring; |
| 19 | use crate::IO_ALIGN; |
| 20 | |
| 21 | /// Rotation order: indices into `Manifest::experts`, in (layer, expert) |
| 22 | /// order, hot-resident experts removed. |
| 23 | #[derive(Debug, Clone)] |
| 24 | pub struct Schedule { |
| 25 | pub items: Vec<usize>, |
| 26 | } |
| 27 | |
| 28 | impl Schedule { |
| 29 | pub fn layer_order(m: &Manifest, hot: &HashSet<(u16, u16)>) -> Self { |
| 30 | let mut items: Vec<usize> = (0..m.experts.len()) |
| 31 | .filter(|&i| !hot.contains(&(m.experts[i].layer, m.experts[i].expert))) |
| 32 | .collect(); |
| 33 | items.sort_by_key(|&i| (m.experts[i].layer, m.experts[i].expert)); |
| 34 | Self { items } |
| 35 | } |
| 36 | |
| 37 | pub fn bytes(&self, m: &Manifest) -> u64 { |
| 38 | self.items.iter().map(|&i| m.experts[i].len).sum() |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone)] |
| 43 | pub struct StreamConfig { |
| 44 | pub slots: usize, |
| 45 | pub workers: usize, |
| 46 | /// Open shards with O_DIRECT (bypass page cache). |
| 47 | pub direct: bool, |
| 48 | /// Verify digest and publish (true), or read and discard without |
| 49 | /// publishing (false; used only to measure raw read cost). |
| 50 | pub publish: bool, |
| 51 | /// How long a writer waits for readers to release a slot before failing. |
| 52 | pub lease_wait: Duration, |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Clone, Default)] |
| 56 | pub struct RotationStats { |
| 57 | pub experts: u64, |
| 58 | /// Expert payload bytes (what a reader sees). |
| 59 | pub payload_bytes: u64, |
| 60 | /// Bytes actually read from the device (aligned windows). |
| 61 | pub device_bytes: u64, |
| 62 | pub wall: Duration, |
| 63 | /// Summed over workers. |
| 64 | pub read_time: Duration, |
| 65 | pub digest_time: Duration, |
| 66 | pub lease_wait_time: Duration, |
| 67 | } |
| 68 | |
| 69 | impl RotationStats { |
| 70 | pub fn payload_gbps(&self) -> f64 { |
| 71 | self.payload_bytes as f64 / self.wall.as_secs_f64() / 1e9 |
| 72 | } |
| 73 | pub fn device_gbps(&self) -> f64 { |
| 74 | self.device_bytes as f64 / self.wall.as_secs_f64() / 1e9 |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | pub struct Streamer { |
| 79 | files: Vec<File>, |
| 80 | cfg: StreamConfig, |
| 81 | } |
| 82 | |
| 83 | impl Streamer { |
| 84 | pub fn open(shards: &[PathBuf], cfg: StreamConfig) -> Result<Self, HeartbeatError> { |
| 85 | assert!(cfg.slots > 0 && cfg.workers > 0 && cfg.workers <= cfg.slots); |
| 86 | let mut files = Vec::with_capacity(shards.len()); |
| 87 | for p in shards { |
| 88 | let mut o = OpenOptions::new(); |
| 89 | o.read(true); |
| 90 | if cfg.direct { |
| 91 | o.custom_flags(libc::O_DIRECT); |
| 92 | } |
| 93 | files.push( |
| 94 | o.open(p) |
| 95 | .map_err(|e| HeartbeatError::io(p.display().to_string(), e))?, |
| 96 | ); |
| 97 | } |
| 98 | Ok(Self { files, cfg }) |
| 99 | } |
| 100 | |
| 101 | pub fn config(&self) -> &StreamConfig { |
| 102 | &self.cfg |
| 103 | } |
| 104 | |
| 105 | /// Bytes each slot needs for the largest aligned window in `m`. |
| 106 | pub fn slot_bytes(m: &Manifest) -> usize { |
| 107 | // Each segment gets its own aligned window; worst case it starts one |
| 108 | // byte before an alignment boundary. |
| 109 | m.experts |
| 110 | .iter() |
| 111 | .map(|e| { |
| 112 | e.segments |
| 113 | .iter() |
| 114 | .map(|s| round_up(s.len as usize + IO_ALIGN, IO_ALIGN)) |
| 115 | .sum::<usize>() |
| 116 | }) |
| 117 | .max() |
| 118 | .unwrap_or(IO_ALIGN) |
| 119 | } |
| 120 | |
| 121 | /// Run one full rotation over `schedule`. Any error fails the ring closed |
| 122 | /// and stops every worker. |
| 123 | pub fn rotate( |
| 124 | &self, |
| 125 | ring: &Ring, |
| 126 | m: &Manifest, |
| 127 | schedule: &Schedule, |
| 128 | ) -> Result<RotationStats, HeartbeatError> { |
| 129 | assert_eq!(ring.num_slots(), self.cfg.slots); |
| 130 | let read_ns = AtomicU64::new(0); |
| 131 | let digest_ns = AtomicU64::new(0); |
| 132 | let wait_ns = AtomicU64::new(0); |
| 133 | let device = AtomicU64::new(0); |
| 134 | let t0 = Instant::now(); |
| 135 | let results: Vec<Result<(), HeartbeatError>> = std::thread::scope(|sc| { |
| 136 | let handles: Vec<_> = (0..self.cfg.workers) |
| 137 | .map(|w| { |
| 138 | let (read_ns, digest_ns, wait_ns, device) = |
| 139 | (&read_ns, &digest_ns, &wait_ns, &device); |
| 140 | sc.spawn(move || -> Result<(), HeartbeatError> { |
| 141 | for (i, &ei) in schedule.items.iter().enumerate() { |
| 142 | let slot = i % self.cfg.slots; |
| 143 | if slot % self.cfg.workers != w { |
| 144 | continue; |
| 145 | } |
| 146 | if ring.is_failed() { |
| 147 | return Err(HeartbeatError::RingFailed); |
| 148 | } |
| 149 | let e = &m.experts[ei]; |
| 150 | let (r, d, wt, dev) = self.load_one(ring, slot, e)?; |
| 151 | read_ns.fetch_add(r.as_nanos() as u64, Ordering::Relaxed); |
| 152 | digest_ns.fetch_add(d.as_nanos() as u64, Ordering::Relaxed); |
| 153 | wait_ns.fetch_add(wt.as_nanos() as u64, Ordering::Relaxed); |
| 154 | device.fetch_add(dev, Ordering::Relaxed); |
| 155 | } |
| 156 | Ok(()) |
| 157 | }) |
| 158 | }) |
| 159 | .collect(); |
| 160 | handles |
| 161 | .into_iter() |
| 162 | .map(|h| h.join().unwrap_or(Err(HeartbeatError::RingFailed))) |
| 163 | .collect() |
| 164 | }); |
| 165 | let wall = t0.elapsed(); |
| 166 | // Report the root cause, not the RingFailed echoes from other workers. |
| 167 | let mut first_err = None; |
| 168 | for r in results { |
| 169 | if let Err(e) = r { |
| 170 | if first_err.is_none() || matches!(first_err, Some(HeartbeatError::RingFailed)) { |
| 171 | first_err = Some(e); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | if let Some(e) = first_err { |
| 176 | ring.fail(); |
| 177 | return Err(e); |
| 178 | } |
| 179 | Ok(RotationStats { |
| 180 | experts: schedule.items.len() as u64, |
| 181 | payload_bytes: schedule.bytes(m), |
| 182 | device_bytes: device.into_inner(), |
| 183 | wall, |
| 184 | read_time: Duration::from_nanos(read_ns.into_inner()), |
| 185 | digest_time: Duration::from_nanos(digest_ns.into_inner()), |
| 186 | lease_wait_time: Duration::from_nanos(wait_ns.into_inner()), |
| 187 | }) |
| 188 | } |
| 189 | |
| 190 | fn load_one( |
| 191 | &self, |
| 192 | ring: &Ring, |
| 193 | slot: usize, |
| 194 | e: &ExpertEntry, |
| 195 | ) -> Result<(Duration, Duration, Duration, u64), HeartbeatError> { |
| 196 | let expected = e.digest_bytes()?; |
| 197 | let (mut g, waited) = ring.begin_fill(slot, self.cfg.lease_wait)?; |
| 198 | let cap = g.buf_mut().len(); |
| 199 | let t_read = Instant::now(); |
| 200 | let mut ranges = Vec::with_capacity(e.segments.len()); |
| 201 | let mut base = 0usize; // aligned position of this segment's window in the slot |
| 202 | let mut device = 0u64; |
| 203 | for seg in &e.segments { |
| 204 | let astart = round_down(seg.start, IO_ALIGN as u64); |
| 205 | let off = (seg.start - astart) as usize; |
| 206 | let need = off + seg.len as usize; |
| 207 | let window = round_up(need, IO_ALIGN); |
| 208 | if base + window > cap { |
| 209 | g.fail(); |
| 210 | return Err(HeartbeatError::PayloadTooLarge { |
| 211 | slot, |
| 212 | need: base + window, |
| 213 | cap, |
| 214 | }); |
| 215 | } |
| 216 | let file = &self.files[seg.shard as usize]; |
| 217 | let buf = &mut g.buf_mut()[base..base + window]; |
| 218 | let mut got = 0usize; |
| 219 | while got < need { |
| 220 | match file.read_at(&mut buf[got..], astart + got as u64) { |
| 221 | Ok(0) => break, |
| 222 | Ok(n) => got += n, |
| 223 | Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {} |
| 224 | Err(err) => { |
| 225 | g.fail(); |
| 226 | return Err(HeartbeatError::io( |
| 227 | format!("pread expert ({},{})", e.layer, e.expert), |
| 228 | err, |
| 229 | )); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | if got < need { |
| 234 | g.fail(); |
| 235 | return Err(HeartbeatError::ShortRead { |
| 236 | expert: (e.layer, e.expert), |
| 237 | wanted: need, |
| 238 | got, |
| 239 | }); |
| 240 | } |
| 241 | ranges.push((base + off, seg.len as usize)); |
| 242 | device += got as u64; |
| 243 | base += window; |
| 244 | } |
| 245 | let read = t_read.elapsed(); |
| 246 | let digest = if self.cfg.publish { |
| 247 | g.publish(e.layer, e.expert, &ranges, &expected)?.1 |
| 248 | } else { |
| 249 | g.discard(); |
| 250 | Duration::ZERO |
| 251 | }; |
| 252 | Ok((read, digest, waited, device)) |
| 253 | } |
| 254 | } |