synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / energy.rs
| 1 | //! On-board CPU energy readings for measurement windows (read-only). |
| 2 | //! |
| 3 | //! Meter: the `aien_spbm` hwmon device (read-only reader of the GB10 SPBM firmware |
| 4 | //! block; `omega-r15/research/m15/spbm/README.md`). Energy channels are 32-bit |
| 5 | //! millijoule counters exposed as microjoules; power channels are milliwatts exposed |
| 6 | //! as microwatts. The firmware publishes no accuracy specification and the readings |
| 7 | //! were never compared with an external meter, so absolute accuracy is not claimed. |
| 8 | //! `pkg` is the SoC package (CPU clusters plus uncore and memory side); the NVMe drive |
| 9 | //! and the rest of the system are outside it and stay UNMEASURED. The boundary of the |
| 10 | //! `sys_total` power channel is not documented (UNVERIFIED) and is kept as supporting |
| 11 | //! data only. |
| 12 | //! |
| 13 | //! Method: the Omega TY-4/TY-5 energy protocol |
| 14 | //! (`omega/docs/turing/TURING_YIELD_ENERGY_PROTOCOL_V0.md` sections 7 to 9), adapted to |
| 15 | //! this harness: a 10 Hz sampler pinned to CPU 0 (an A725 core) records pkg, cpu_e and |
| 16 | //! cpu_p; a window is refused, never repaired, when the meter is missing, an overflow |
| 17 | //! flag is set at either edge, a counter decreased, the counter is within one window of |
| 18 | //! the 32-bit wrap, two consecutive samples are more than 300 ms apart, or fewer than |
| 19 | //! 90% of the expected samples arrived. Each edge is uncertain by up to one sensor |
| 20 | //! period (about 0.1 s) of power; the analytic edge bound is reported. The idle share is |
| 21 | //! subtracted from a separate IDLE window measured the same way (a COUNTERFACTUAL |
| 22 | //! estimate, not a direct reading). Other processes on the host are a confounder: the |
| 23 | //! window records `/proc/loadavg` and whole-machine busy CPU time at both edges. |
| 24 | |
| 25 | use serde::{Deserialize, Serialize}; |
| 26 | use std::path::{Path, PathBuf}; |
| 27 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 28 | use std::sync::{Arc, Mutex}; |
| 29 | use std::time::{Duration, Instant}; |
| 30 | |
| 31 | /// Sampler period (10 Hz, as in the TY protocol). |
| 32 | pub const SAMPLE_PERIOD: Duration = Duration::from_millis(100); |
| 33 | /// Sensor update period assumed for the analytic edge bound (TY protocol section 7). |
| 34 | pub const SENSOR_PERIOD_S: f64 = 0.1; |
| 35 | /// 32-bit millijoule counter wrap, in microjoules. |
| 36 | pub const COUNTER_WRAP_UJ: u64 = (u32::MAX as u64 + 1) * 1000; |
| 37 | /// Refuse a window when two consecutive samples are further apart than this. |
| 38 | pub const MAX_SAMPLE_GAP: Duration = Duration::from_millis(300); |
| 39 | /// Where the kernel lists hwmon devices. |
| 40 | pub const HWMON_ROOT: &str = "/sys/class/hwmon"; |
| 41 | |
| 42 | /// A located hwmon device with labelled channels. |
| 43 | #[derive(Debug, Clone)] |
| 44 | pub struct Spbm { |
| 45 | dir: PathBuf, |
| 46 | } |
| 47 | |
| 48 | fn read_trim(path: &Path) -> Option<String> { |
| 49 | std::fs::read_to_string(path) |
| 50 | .ok() |
| 51 | .map(|s| s.trim().to_string()) |
| 52 | } |
| 53 | |
| 54 | impl Spbm { |
| 55 | /// Find the hwmon device named `aien_spbm`. |
| 56 | pub fn find() -> Option<Self> { |
| 57 | Self::find_in(Path::new(HWMON_ROOT)) |
| 58 | } |
| 59 | |
| 60 | /// Find the hwmon device named `aien_spbm` under `root` (normally [`HWMON_ROOT`]). |
| 61 | pub fn find_in(root: &Path) -> Option<Self> { |
| 62 | let entries = std::fs::read_dir(root).ok()?; |
| 63 | for e in entries.flatten() { |
| 64 | let dir = e.path(); |
| 65 | if read_trim(&dir.join("name")).as_deref() == Some("aien_spbm") { |
| 66 | return Some(Self { dir }); |
| 67 | } |
| 68 | } |
| 69 | None |
| 70 | } |
| 71 | |
| 72 | fn channel_index(&self, kind: &str, label: &str) -> Option<usize> { |
| 73 | (1..=16).find(|n| { |
| 74 | read_trim(&self.dir.join(format!("{kind}{n}_label"))).as_deref() == Some(label) |
| 75 | }) |
| 76 | } |
| 77 | |
| 78 | /// Energy counter in microjoules (`pkg`, `cpu_e`, `cpu_p`, `gpm`). `None` when the |
| 79 | /// read fails (the reader returns `EOVERFLOW` when an overflow flag is set). |
| 80 | pub fn energy_uj(&self, label: &str) -> Option<u64> { |
| 81 | let n = self.channel_index("energy", label)?; |
| 82 | read_trim(&self.dir.join(format!("energy{n}_input")))? |
| 83 | .parse() |
| 84 | .ok() |
| 85 | } |
| 86 | |
| 87 | /// Raw overflow indicator of an energy channel (0 means no overflow). |
| 88 | pub fn overflow_raw(&self, label: &str) -> Option<u64> { |
| 89 | let n = self.channel_index("energy", label)?; |
| 90 | read_trim(&self.dir.join(format!("energy{n}_overflow_raw")))? |
| 91 | .parse() |
| 92 | .ok() |
| 93 | } |
| 94 | |
| 95 | /// Instantaneous power in microwatts (`sys_total`, `soc_pkg`, `cpu_e`, `cpu_p`, `gpu`). |
| 96 | pub fn power_uw(&self, label: &str) -> Option<u64> { |
| 97 | let n = self.channel_index("power", label)?; |
| 98 | read_trim(&self.dir.join(format!("power{n}_input")))? |
| 99 | .parse() |
| 100 | .ok() |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// NVMe composite temperature in kelvin from the `nvme` hwmon device, if present. |
| 105 | pub fn nvme_temperature_k() -> Option<f64> { |
| 106 | let entries = std::fs::read_dir("/sys/class/hwmon").ok()?; |
| 107 | for e in entries.flatten() { |
| 108 | let dir = e.path(); |
| 109 | if read_trim(&dir.join("name")).as_deref() == Some("nvme") { |
| 110 | let milli_c: f64 = read_trim(&dir.join("temp1_input"))?.parse().ok()?; |
| 111 | return Some(milli_c / 1000.0 + 273.15); |
| 112 | } |
| 113 | } |
| 114 | None |
| 115 | } |
| 116 | |
| 117 | /// `/proc/loadavg` first three fields. |
| 118 | pub fn loadavg() -> Option<[f64; 3]> { |
| 119 | let s = read_trim(Path::new("/proc/loadavg"))?; |
| 120 | let mut it = s.split_whitespace().map(|v| v.parse::<f64>().ok()); |
| 121 | Some([it.next()??, it.next()??, it.next()??]) |
| 122 | } |
| 123 | |
| 124 | /// Whole-machine busy CPU time (all CPUs, user + nice + system + irq + softirq + steal), seconds. |
| 125 | pub fn machine_busy_cpu_s() -> Option<f64> { |
| 126 | let s = std::fs::read_to_string("/proc/stat").ok()?; |
| 127 | let line = s.lines().find(|l| l.starts_with("cpu "))?; |
| 128 | let v: Vec<u64> = line |
| 129 | .split_whitespace() |
| 130 | .skip(1) |
| 131 | .filter_map(|x| x.parse().ok()) |
| 132 | .collect(); |
| 133 | // user nice system idle iowait irq softirq steal |
| 134 | let busy = v.first()? + v.get(1)? + v.get(2)? + v.get(5)? + v.get(6)? + v.get(7)?; |
| 135 | // SAFETY: sysconf has no preconditions. |
| 136 | let hz = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; |
| 137 | (hz > 0).then(|| busy as f64 / hz as f64) |
| 138 | } |
| 139 | |
| 140 | #[derive(Debug, Clone, Copy)] |
| 141 | struct Sample { |
| 142 | t: Instant, |
| 143 | pkg: Option<u64>, |
| 144 | cpu_e: Option<u64>, |
| 145 | cpu_p: Option<u64>, |
| 146 | sys_total_uw: Option<u64>, |
| 147 | } |
| 148 | |
| 149 | fn take_sample(s: &Spbm) -> Sample { |
| 150 | Sample { |
| 151 | t: Instant::now(), |
| 152 | pkg: s.energy_uj("pkg"), |
| 153 | cpu_e: s.energy_uj("cpu_e"), |
| 154 | cpu_p: s.energy_uj("cpu_p"), |
| 155 | sys_total_uw: s.power_uw("sys_total"), |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// Energy over one measurement window. Joule fields are `None` when the window was |
| 160 | /// refused (`refusal` says why) or the meter is absent. |
| 161 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 162 | pub struct EnergyReading { |
| 163 | /// Meter description, or `UNMEASURED: <reason>`. |
| 164 | pub sensor: String, |
| 165 | pub window_s: f64, |
| 166 | pub valid: bool, |
| 167 | pub refusal: Option<String>, |
| 168 | pub samples: usize, |
| 169 | pub largest_gap_ms: Option<f64>, |
| 170 | /// SoC package energy, joules (DIRECT reading for this interval). |
| 171 | pub pkg_j: Option<f64>, |
| 172 | pub cpu_p_j: Option<f64>, |
| 173 | pub cpu_e_j: Option<f64>, |
| 174 | /// pkg - cpu_p - cpu_e (uncore and memory side). |
| 175 | pub rest_j: Option<f64>, |
| 176 | /// Mean pkg power over the window, watts. |
| 177 | pub pkg_mean_w: Option<f64>, |
| 178 | /// Analytic sd of the pkg energy from both edges: `P * 0.1 s * sqrt(2/3)`, joules. |
| 179 | pub pkg_edge_sd_j: Option<f64>, |
| 180 | /// Mean of the `sys_total` power samples, watts (boundary UNVERIFIED; supporting only). |
| 181 | pub sys_total_mean_w: Option<f64>, |
| 182 | pub nvme_temp_k: Option<f64>, |
| 183 | pub loadavg_start: Option<[f64; 3]>, |
| 184 | pub loadavg_end: Option<[f64; 3]>, |
| 185 | /// Busy CPU seconds of the whole machine over the window (all processes). |
| 186 | pub machine_busy_cpu_s: Option<f64>, |
| 187 | } |
| 188 | |
| 189 | impl EnergyReading { |
| 190 | /// Package joules above an idle baseline power for this window's length |
| 191 | /// (idle share is a COUNTERFACTUAL estimate from a separate IDLE window). |
| 192 | pub fn pkg_above_idle_j(&self, idle: &EnergyReading) -> Option<f64> { |
| 193 | let p_idle = idle.pkg_mean_w?; |
| 194 | Some(self.pkg_j? - p_idle * self.window_s) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// An open measurement window; call [`EnergyWindow::finish`] to close it. |
| 199 | pub struct EnergyWindow { |
| 200 | spbm: Option<Spbm>, |
| 201 | start: Instant, |
| 202 | first: Option<Sample>, |
| 203 | overflow_start: bool, |
| 204 | stop: Arc<AtomicBool>, |
| 205 | samples: Arc<Mutex<Vec<Sample>>>, |
| 206 | sampler: Option<std::thread::JoinHandle<()>>, |
| 207 | loadavg_start: Option<[f64; 3]>, |
| 208 | busy_start: Option<f64>, |
| 209 | } |
| 210 | |
| 211 | fn pin_current_thread_to_cpu0() { |
| 212 | // SAFETY: `set` is a zeroed cpu_set_t; CPU_SET and sched_setaffinity(0, ...) only |
| 213 | // touch it and the calling thread's affinity. Failure is harmless (sampler unpinned). |
| 214 | unsafe { |
| 215 | let mut set: libc::cpu_set_t = std::mem::zeroed(); |
| 216 | libc::CPU_SET(0, &mut set); |
| 217 | let _ = libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn any_overflow(s: &Spbm) -> bool { |
| 222 | ["pkg", "cpu_e", "cpu_p"] |
| 223 | .iter() |
| 224 | .any(|l| s.overflow_raw(l).is_none_or(|v| v != 0)) |
| 225 | } |
| 226 | |
| 227 | impl EnergyWindow { |
| 228 | /// Start a window: check overflow flags, take the first sample, start the 10 Hz sampler. |
| 229 | pub fn start() -> Self { |
| 230 | let spbm = Spbm::find(); |
| 231 | let stop = Arc::new(AtomicBool::new(false)); |
| 232 | let samples = Arc::new(Mutex::new(Vec::new())); |
| 233 | let loadavg_start = loadavg(); |
| 234 | let busy_start = machine_busy_cpu_s(); |
| 235 | let overflow_start = spbm.as_ref().is_some_and(any_overflow); |
| 236 | let first = spbm.as_ref().map(take_sample); |
| 237 | let sampler = spbm.clone().map(|s| { |
| 238 | let (stop, samples) = (stop.clone(), samples.clone()); |
| 239 | std::thread::spawn(move || { |
| 240 | pin_current_thread_to_cpu0(); |
| 241 | let mut next = Instant::now() + SAMPLE_PERIOD; |
| 242 | while !stop.load(Ordering::Relaxed) { |
| 243 | let now = Instant::now(); |
| 244 | if now < next { |
| 245 | std::thread::sleep((next - now).min(Duration::from_millis(5))); |
| 246 | continue; |
| 247 | } |
| 248 | let sm = take_sample(&s); |
| 249 | if let Ok(mut v) = samples.lock() { |
| 250 | v.push(sm); |
| 251 | } |
| 252 | next += SAMPLE_PERIOD; |
| 253 | } |
| 254 | }) |
| 255 | }); |
| 256 | Self { |
| 257 | spbm, |
| 258 | start: Instant::now(), |
| 259 | first, |
| 260 | overflow_start, |
| 261 | stop, |
| 262 | samples, |
| 263 | sampler, |
| 264 | loadavg_start, |
| 265 | busy_start, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | /// Close the window, apply the refusal rules, and return the reading. |
| 270 | pub fn finish(mut self) -> EnergyReading { |
| 271 | let last = self.spbm.as_ref().map(take_sample); |
| 272 | let window_s = self.start.elapsed().as_secs_f64(); |
| 273 | self.stop.store(true, Ordering::Relaxed); |
| 274 | if let Some(h) = self.sampler.take() { |
| 275 | let _ = h.join(); |
| 276 | } |
| 277 | let overflow_end = self.spbm.as_ref().is_some_and(any_overflow); |
| 278 | let mut all: Vec<Sample> = Vec::new(); |
| 279 | all.extend(self.first); |
| 280 | all.extend(self.samples.lock().map(|v| v.clone()).unwrap_or_default()); |
| 281 | all.extend(last); |
| 282 | let mut r = EnergyReading { |
| 283 | sensor: "UNMEASURED: no aien_spbm hwmon device on this host".into(), |
| 284 | window_s, |
| 285 | samples: all.len(), |
| 286 | nvme_temp_k: nvme_temperature_k(), |
| 287 | loadavg_start: self.loadavg_start, |
| 288 | loadavg_end: loadavg(), |
| 289 | machine_busy_cpu_s: match (self.busy_start, machine_busy_cpu_s()) { |
| 290 | (Some(a), Some(b)) => Some(b - a), |
| 291 | _ => None, |
| 292 | }, |
| 293 | ..Default::default() |
| 294 | }; |
| 295 | if self.spbm.is_none() { |
| 296 | r.refusal = Some("meter unavailable".into()); |
| 297 | return r; |
| 298 | } |
| 299 | r.sensor = "aien_spbm hwmon, SoC package only (GB10 SPBM firmware counters: energy 1 mJ \ |
| 300 | step, update about 0.1 s, sampled at 10 Hz; no published accuracy; not \ |
| 301 | compared with an external meter)" |
| 302 | .into(); |
| 303 | let gaps: Vec<Duration> = all.windows(2).map(|w| w[1].t - w[0].t).collect(); |
| 304 | r.largest_gap_ms = gaps |
| 305 | .iter() |
| 306 | .max() |
| 307 | .map(|g| (g.as_secs_f64() * 1e6).round() / 1e3); |
| 308 | let sys: Vec<u64> = all.iter().filter_map(|s| s.sys_total_uw).collect(); |
| 309 | if !sys.is_empty() { |
| 310 | r.sys_total_mean_w = Some(sys.iter().sum::<u64>() as f64 / sys.len() as f64 / 1e6); |
| 311 | } |
| 312 | let expected = (window_s / SAMPLE_PERIOD.as_secs_f64()).floor() as usize; |
| 313 | let delta = |f: fn(&Sample) -> Option<u64>| -> Result<u64, String> { |
| 314 | let mut prev: Option<u64> = None; |
| 315 | for s in &all { |
| 316 | let v = f(s).ok_or("counter read failed (overflow or missing)")?; |
| 317 | if prev.is_some_and(|p| v < p) { |
| 318 | return Err("energy counter decreased".into()); |
| 319 | } |
| 320 | prev = Some(v); |
| 321 | } |
| 322 | let (a, b) = ( |
| 323 | f(all.first().ok_or("no samples")?), |
| 324 | f(all.last().ok_or("no samples")?), |
| 325 | ); |
| 326 | let (a, b) = (a.ok_or("no start reading")?, b.ok_or("no end reading")?); |
| 327 | if COUNTER_WRAP_UJ.saturating_sub(b) <= b - a { |
| 328 | return Err("counter within one window of the 32-bit wrap".into()); |
| 329 | } |
| 330 | Ok(b - a) |
| 331 | }; |
| 332 | let refusal = if self.overflow_start || overflow_end { |
| 333 | Some("overflow flag set at a window edge".to_string()) |
| 334 | } else if gaps.iter().any(|g| *g > MAX_SAMPLE_GAP) { |
| 335 | Some("gap between consecutive samples above 300 ms".into()) |
| 336 | } else if all.len().saturating_sub(2) * 10 < expected * 9 { |
| 337 | Some(format!( |
| 338 | "fewer than 90% of expected samples ({} of {expected})", |
| 339 | all.len().saturating_sub(2) |
| 340 | )) |
| 341 | } else { |
| 342 | None |
| 343 | }; |
| 344 | let deltas = (delta(|s| s.pkg), delta(|s| s.cpu_p), delta(|s| s.cpu_e)); |
| 345 | match (refusal, deltas) { |
| 346 | (Some(why), _) => r.refusal = Some(why), |
| 347 | (None, (Ok(pkg), Ok(cpu_p), Ok(cpu_e))) => { |
| 348 | let j = |uj: u64| uj as f64 / 1e6; |
| 349 | r.valid = true; |
| 350 | r.pkg_j = Some(j(pkg)); |
| 351 | r.cpu_p_j = Some(j(cpu_p)); |
| 352 | r.cpu_e_j = Some(j(cpu_e)); |
| 353 | r.rest_j = Some(j(pkg) - j(cpu_p) - j(cpu_e)); |
| 354 | if window_s > 0.0 { |
| 355 | let p = j(pkg) / window_s; |
| 356 | r.pkg_mean_w = Some(p); |
| 357 | r.pkg_edge_sd_j = Some(p * SENSOR_PERIOD_S * (2.0f64 / 3.0).sqrt()); |
| 358 | } |
| 359 | } |
| 360 | (None, (a, b, c)) => { |
| 361 | r.refusal = [a.err(), b.err(), c.err()].into_iter().flatten().next(); |
| 362 | } |
| 363 | } |
| 364 | r |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// Measure an IDLE window of `length` (the harness sleeps; other tenants keep running). |
| 369 | pub fn idle_window(length: Duration) -> EnergyReading { |
| 370 | let w = EnergyWindow::start(); |
| 371 | std::thread::sleep(length); |
| 372 | w.finish() |
| 373 | } |