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-kv-bench / src / bin / bench_persistent_kv.rs
| 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 | //! `bench_persistent_kv`: persistent KV benchmark on the host CPU reference |
| 17 | //! backend (cut C9, sc#485). Writes one JSON report (schema |
| 18 | //! `aien.pkv.bench.v1`) and prints the generated Markdown table. |
| 19 | //! |
| 20 | //! ```text |
| 21 | //! bench_persistent_kv --modes resident-only,cold-prefill,restore-from-page-cache,restore-from-device \ |
| 22 | //! --out benchmarks/data/persistent_kv_host_<stamp>.json \ |
| 23 | //! [--concurrency 1,2,4,8] [--prompt-tokens 512,2048] [--rounds 3] [--store-root DIR] |
| 24 | //! bench_persistent_kv --render <report.json> |
| 25 | //! ``` |
| 26 | //! |
| 27 | //! There is no default mode: the operator names every mode, and each row is |
| 28 | //! labelled with its mode, platform and cache_state. `restore-from-device` |
| 29 | //! and the native physical rows are always NOT_RUN here (no root, no native |
| 30 | //! hardware). Never touches a GPU. |
| 31 | |
| 32 | use aien_kv_bench::report::{ |
| 33 | build_report, check_report, render_markdown, Machine, Report, ReportMeta, Row, Workload, HOSTED, |
| 34 | }; |
| 35 | use aien_kv_bench::run::{model_label, run_row, Mode, RunSpec, DEVICE_NOT_RUN_REASON}; |
| 36 | use std::path::PathBuf; |
| 37 | use std::process::{Command, ExitCode}; |
| 38 | |
| 39 | const USAGE: &str = "usage: bench_persistent_kv --modes <m1,m2,...> --out <file.json> [--concurrency 1,2,4,8] [--prompt-tokens 512,2048] [--rounds N] [--store-root DIR]\n bench_persistent_kv --render <file.json>\nmodes: resident-only, cold-prefill, restore-from-page-cache, restore-from-device"; |
| 40 | |
| 41 | struct Args { |
| 42 | modes: Vec<Mode>, |
| 43 | out: PathBuf, |
| 44 | concurrency: Vec<u32>, |
| 45 | prompt_tokens: Vec<u32>, |
| 46 | rounds: u32, |
| 47 | store_root: PathBuf, |
| 48 | } |
| 49 | |
| 50 | fn parse_list(flag: &str, v: &str) -> Result<Vec<u32>, String> { |
| 51 | v.split(',') |
| 52 | .map(|s| { |
| 53 | s.trim() |
| 54 | .parse::<u32>() |
| 55 | .ok() |
| 56 | .filter(|n| *n > 0) |
| 57 | .ok_or_else(|| format!("{flag}: {s:?} is not a positive integer")) |
| 58 | }) |
| 59 | .collect() |
| 60 | } |
| 61 | |
| 62 | fn parse_args(argv: &[String]) -> Result<Args, String> { |
| 63 | let mut modes: Option<Vec<Mode>> = None; |
| 64 | let mut out = None; |
| 65 | let mut concurrency = vec![1, 2, 4, 8]; |
| 66 | let mut prompt_tokens = vec![512, 2048]; |
| 67 | let mut rounds = 3; |
| 68 | let mut store_root = PathBuf::from("target/pkv-bench-store"); |
| 69 | let mut it = argv.iter(); |
| 70 | while let Some(flag) = it.next() { |
| 71 | let mut value = || { |
| 72 | it.next() |
| 73 | .cloned() |
| 74 | .ok_or_else(|| format!("{flag} needs a value")) |
| 75 | }; |
| 76 | match flag.as_str() { |
| 77 | "--modes" => { |
| 78 | let v = value()?; |
| 79 | let mut list = Vec::new(); |
| 80 | for label in v.split(',').map(str::trim) { |
| 81 | let mode = Mode::parse(label).ok_or_else(|| { |
| 82 | format!("refusing to report: unknown mode label {label:?}") |
| 83 | })?; |
| 84 | if !list.contains(&mode) { |
| 85 | list.push(mode); |
| 86 | } |
| 87 | } |
| 88 | modes = Some(list); |
| 89 | } |
| 90 | "--out" => out = Some(PathBuf::from(value()?)), |
| 91 | "--concurrency" => concurrency = parse_list(flag, &value()?)?, |
| 92 | "--prompt-tokens" => prompt_tokens = parse_list(flag, &value()?)?, |
| 93 | "--rounds" => rounds = parse_list(flag, &value()?)?.first().copied().unwrap_or(0), |
| 94 | "--store-root" => store_root = PathBuf::from(value()?), |
| 95 | other => return Err(format!("unknown argument {other:?}")), |
| 96 | } |
| 97 | } |
| 98 | let modes = modes.filter(|m| !m.is_empty()).ok_or( |
| 99 | "refusing to report: --modes is required (no default mode; every row is labelled by the mode the operator named)", |
| 100 | )?; |
| 101 | let out = out.ok_or("--out <file.json> is required")?; |
| 102 | if out.exists() { |
| 103 | return Err(format!( |
| 104 | "{} exists; a report is never overwritten", |
| 105 | out.display() |
| 106 | )); |
| 107 | } |
| 108 | Ok(Args { |
| 109 | modes, |
| 110 | out, |
| 111 | concurrency, |
| 112 | prompt_tokens, |
| 113 | rounds, |
| 114 | store_root, |
| 115 | }) |
| 116 | } |
| 117 | |
| 118 | fn sh(cmd: &str, args: &[&str]) -> Result<String, String> { |
| 119 | let o = Command::new(cmd) |
| 120 | .args(args) |
| 121 | .output() |
| 122 | .map_err(|e| format!("{cmd}: {e}"))?; |
| 123 | if !o.status.success() { |
| 124 | return Err(format!( |
| 125 | "{cmd} {args:?}: {}", |
| 126 | String::from_utf8_lossy(&o.stderr).trim() |
| 127 | )); |
| 128 | } |
| 129 | Ok(String::from_utf8_lossy(&o.stdout).trim().to_string()) |
| 130 | } |
| 131 | |
| 132 | fn read_trim(path: &str) -> String { |
| 133 | std::fs::read_to_string(path) |
| 134 | .map(|s| s.trim().to_string()) |
| 135 | .unwrap_or_else(|_| "unknown".into()) |
| 136 | } |
| 137 | |
| 138 | fn machine() -> Machine { |
| 139 | let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").unwrap_or_default(); |
| 140 | let cpu_model = cpuinfo |
| 141 | .lines() |
| 142 | .find_map(|l| { |
| 143 | let (k, v) = l.split_once(':')?; |
| 144 | matches!(k.trim(), "model name" | "Model name" | "Hardware").then(|| v.trim()) |
| 145 | }) |
| 146 | .unwrap_or("unknown (no model name in /proc/cpuinfo)") |
| 147 | .to_string(); |
| 148 | // Field 19 of /proc/self/stat is the nice value (after the ")" of comm). |
| 149 | let nice = std::fs::read_to_string("/proc/self/stat") |
| 150 | .ok() |
| 151 | .and_then(|s| { |
| 152 | let rest = s.rsplit_once(')')?.1.to_string(); |
| 153 | rest.split_whitespace().nth(16)?.parse::<i64>().ok() |
| 154 | }) |
| 155 | .unwrap_or(0); |
| 156 | Machine { |
| 157 | hostname: read_trim("/proc/sys/kernel/hostname"), |
| 158 | kernel: read_trim("/proc/sys/kernel/osrelease"), |
| 159 | arch: std::env::consts::ARCH.to_string(), |
| 160 | cpu_model, |
| 161 | cpus: std::thread::available_parallelism() |
| 162 | .map(|n| n.get()) |
| 163 | .unwrap_or(0), |
| 164 | nice, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// UTC civil time from the Unix clock (Howard Hinnant's days-to-civil). |
| 169 | fn utc_now() -> (String, String) { |
| 170 | let secs = std::time::SystemTime::now() |
| 171 | .duration_since(std::time::UNIX_EPOCH) |
| 172 | .map(|d| d.as_secs() as i64) |
| 173 | .unwrap_or(0); |
| 174 | let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); |
| 175 | let z = days + 719_468; |
| 176 | let era = z.div_euclid(146_097); |
| 177 | let doe = z - era * 146_097; |
| 178 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 179 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 180 | let mp = (5 * doy + 2) / 153; |
| 181 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 182 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 183 | let y = yoe + era * 400 + i64::from(m <= 2); |
| 184 | let (hh, mm, ss) = (rem / 3600, rem % 3600 / 60, rem % 60); |
| 185 | ( |
| 186 | format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z"), |
| 187 | format!("{y:04}{m:02}{d:02}T{hh:02}{mm:02}{ss:02}Z"), |
| 188 | ) |
| 189 | } |
| 190 | |
| 191 | fn render(path: &str) -> Result<(), String> { |
| 192 | let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; |
| 193 | let report: Report = serde_json::from_str(&text).map_err(|e| format!("{path}: {e}"))?; |
| 194 | check_report(&report).map_err(|e| e.to_string())?; |
| 195 | print!("{}", render_markdown(&report).map_err(|e| e.to_string())?); |
| 196 | Ok(()) |
| 197 | } |
| 198 | |
| 199 | async fn run(args: Args, argv: &[String]) -> Result<(), String> { |
| 200 | let git_sha = sh("git", &["rev-parse", "HEAD"])?; |
| 201 | let git_dirty = !sh("git", &["status", "--porcelain"])?.is_empty(); |
| 202 | let (started_utc, stamp) = utc_now(); |
| 203 | let spec = RunSpec { |
| 204 | modes: args.modes.clone(), |
| 205 | concurrency: args.concurrency.clone(), |
| 206 | prompt_tokens: args.prompt_tokens.clone(), |
| 207 | rounds: args.rounds, |
| 208 | turn1_max_tokens: 8, |
| 209 | turn2_suffix_tokens: 16, |
| 210 | turn2_max_tokens: 16, |
| 211 | block_size: 16, |
| 212 | chunk_blocks: 16, |
| 213 | store_root: args.store_root.clone(), |
| 214 | }; |
| 215 | if spec.rounds == 0 { |
| 216 | return Err("--rounds must be at least 1".into()); |
| 217 | } |
| 218 | let mut rows = Vec::new(); |
| 219 | for &mode in &spec.modes { |
| 220 | if mode == Mode::RestoreDevice { |
| 221 | rows.push(Row::not_run( |
| 222 | mode.label(), |
| 223 | HOSTED, |
| 224 | mode.cache_state(), |
| 225 | DEVICE_NOT_RUN_REASON, |
| 226 | )); |
| 227 | continue; |
| 228 | } |
| 229 | for &prompt in &spec.prompt_tokens { |
| 230 | for &c in &spec.concurrency { |
| 231 | eprintln!("bench: {} c={c} prompt={prompt} ...", mode.label()); |
| 232 | let row = run_row(&spec, mode, c, prompt) |
| 233 | .await |
| 234 | .map_err(|e| format!("{} c={c} prompt={prompt}: {e}", mode.label()))?; |
| 235 | eprintln!( |
| 236 | "bench: p50 {} us, p95 {} us, ttft p50 {} us", |
| 237 | row.p50_us.unwrap_or(0), |
| 238 | row.p95_us.unwrap_or(0), |
| 239 | row.ttft_p50_us.unwrap_or(0) |
| 240 | ); |
| 241 | rows.push(row); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | let meta = ReportMeta { |
| 246 | measurement_id: format!( |
| 247 | "BENCH-PKV-HOST-{stamp}-{}", |
| 248 | &git_sha[..git_sha.len().min(7)] |
| 249 | ), |
| 250 | git_sha, |
| 251 | git_dirty, |
| 252 | command: format!("bench_persistent_kv {}", argv.join(" ")), |
| 253 | started_utc, |
| 254 | platform: HOSTED.to_string(), |
| 255 | machine: machine(), |
| 256 | backend: "NativeTransformerBackend over ReferenceCpuBackend (host CPU, FP32 arithmetic, bf16 KV pool)".into(), |
| 257 | model: model_label(), |
| 258 | workload: Workload { |
| 259 | concurrency: spec.concurrency.clone(), |
| 260 | prompt_tokens: spec.prompt_tokens.clone(), |
| 261 | rounds: spec.rounds, |
| 262 | turn1_max_tokens: spec.turn1_max_tokens as u32, |
| 263 | turn2_suffix_tokens: spec.turn2_suffix_tokens as u32, |
| 264 | turn2_max_tokens: spec.turn2_max_tokens as u32, |
| 265 | block_size: spec.block_size as u32, |
| 266 | chunk_blocks: spec.chunk_blocks, |
| 267 | dispatch_depth: aien_kv_store::worker::WorkerConfig::default().dispatch_depth, |
| 268 | }, |
| 269 | }; |
| 270 | let report = build_report(meta, rows).map_err(|e| e.to_string())?; |
| 271 | let json = serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?; |
| 272 | std::fs::write(&args.out, json + "\n").map_err(|e| format!("{}: {e}", args.out.display()))?; |
| 273 | eprintln!("bench: wrote {}", args.out.display()); |
| 274 | print!("{}", render_markdown(&report).map_err(|e| e.to_string())?); |
| 275 | Ok(()) |
| 276 | } |
| 277 | |
| 278 | fn main() -> ExitCode { |
| 279 | let argv: Vec<String> = std::env::args().skip(1).collect(); |
| 280 | if argv.first().map(String::as_str) == Some("--render") { |
| 281 | return match argv |
| 282 | .get(1) |
| 283 | .ok_or("--render needs a file".to_string()) |
| 284 | .and_then(|p| render(p)) |
| 285 | { |
| 286 | Ok(()) => ExitCode::SUCCESS, |
| 287 | Err(e) => { |
| 288 | eprintln!("bench_persistent_kv: {e}"); |
| 289 | ExitCode::from(2) |
| 290 | } |
| 291 | }; |
| 292 | } |
| 293 | let args = match parse_args(&argv) { |
| 294 | Ok(a) => a, |
| 295 | Err(e) => { |
| 296 | eprintln!("bench_persistent_kv: {e}\n{USAGE}"); |
| 297 | return ExitCode::from(2); |
| 298 | } |
| 299 | }; |
| 300 | let rt = match tokio::runtime::Builder::new_current_thread() |
| 301 | .enable_all() |
| 302 | .build() |
| 303 | { |
| 304 | Ok(rt) => rt, |
| 305 | Err(e) => { |
| 306 | eprintln!("bench_persistent_kv: tokio: {e}"); |
| 307 | return ExitCode::from(1); |
| 308 | } |
| 309 | }; |
| 310 | match rt.block_on(run(args, &argv)) { |
| 311 | Ok(()) => ExitCode::SUCCESS, |
| 312 | Err(e) => { |
| 313 | eprintln!("bench_persistent_kv: {e}"); |
| 314 | ExitCode::from(1) |
| 315 | } |
| 316 | } |
| 317 | } |