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 / run.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 | //! The measuring half of `bench_persistent_kv`: drives the real runtime spine, |
| 17 | //! the real scheduler and the native transformer backend on the host CPU |
| 18 | //! reference arithmetic (`ReferenceCpuBackend`, reference test weights), with |
| 19 | //! the C4 host filesystem store through the daemon wiring |
| 20 | //! (`shared_kv::enable_persistent_kv`) for the restore mode. Host only: no |
| 21 | //! GPU, no CUDA, no root. |
| 22 | |
| 23 | use crate::report::{Row, HOSTED}; |
| 24 | use aien_abi_core::{ModelConfig, SamplingParams}; |
| 25 | use aien_inference_abi::backend::TensorBackend; |
| 26 | use aien_inference_abi::{NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights}; |
| 27 | use aien_runtime::shared_kv::{ |
| 28 | build_shared_kv_runtime, enable_persistent_kv, KvPersistSettings, ModelKvBinding, |
| 29 | SharedKvSizing, KV_CHUNK_BLOCKS_ENV, KV_RESTORE_MAX_BLOCKS_ENV, KV_STORE_DIR_ENV, |
| 30 | }; |
| 31 | use aien_runtime::spine::AienRuntimeSpine; |
| 32 | use aien_scheduler::{ChannelCompletionSink, CompletionEvent, SchedulerConfig}; |
| 33 | use std::collections::HashMap; |
| 34 | use std::path::PathBuf; |
| 35 | use std::sync::Arc; |
| 36 | use std::time::{Duration, Instant}; |
| 37 | |
| 38 | /// The vocabulary of the reference test model; every token id is below it. |
| 39 | pub const VOCAB: u32 = 97; |
| 40 | |
| 41 | /// A stop id the model can never produce. |
| 42 | const NO_EOS: u32 = u32::MAX; |
| 43 | |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 45 | pub enum Mode { |
| 46 | ResidentOnly, |
| 47 | ColdPrefill, |
| 48 | RestorePageCache, |
| 49 | RestoreDevice, |
| 50 | } |
| 51 | |
| 52 | impl Mode { |
| 53 | pub const ALL: [Mode; 4] = [ |
| 54 | Mode::ResidentOnly, |
| 55 | Mode::ColdPrefill, |
| 56 | Mode::RestorePageCache, |
| 57 | Mode::RestoreDevice, |
| 58 | ]; |
| 59 | |
| 60 | pub fn label(self) -> &'static str { |
| 61 | match self { |
| 62 | Mode::ResidentOnly => "resident-only", |
| 63 | Mode::ColdPrefill => "cold-prefill", |
| 64 | Mode::RestorePageCache => "restore-from-page-cache", |
| 65 | Mode::RestoreDevice => "restore-from-device", |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub fn parse(s: &str) -> Option<Mode> { |
| 70 | Mode::ALL.into_iter().find(|m| m.label() == s) |
| 71 | } |
| 72 | |
| 73 | pub fn cache_state(self) -> &'static str { |
| 74 | match self { |
| 75 | Mode::ResidentOnly | Mode::ColdPrefill => "none", |
| 76 | Mode::RestorePageCache => "page_cache", |
| 77 | Mode::RestoreDevice => "device", |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn uses_store(self) -> bool { |
| 82 | matches!(self, Mode::RestorePageCache | Mode::RestoreDevice) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Why `restore-from-device` is never measured by this binary. |
| 87 | pub const DEVICE_NOT_RUN_REASON: &str = "a device read needs the page cache dropped (root: /proc/sys/vm/drop_caches) and verified empty with mincore (ADR 0003 section 15.1); this harness never uses sudo, and O_DIRECT reads are cut X1/X2"; |
| 88 | |
| 89 | #[derive(Debug, Clone)] |
| 90 | pub struct RunSpec { |
| 91 | pub modes: Vec<Mode>, |
| 92 | pub concurrency: Vec<u32>, |
| 93 | pub prompt_tokens: Vec<u32>, |
| 94 | pub rounds: u32, |
| 95 | pub turn1_max_tokens: usize, |
| 96 | pub turn2_suffix_tokens: usize, |
| 97 | pub turn2_max_tokens: usize, |
| 98 | pub block_size: usize, |
| 99 | pub chunk_blocks: u32, |
| 100 | pub store_root: PathBuf, |
| 101 | } |
| 102 | |
| 103 | /// The reference model: the C7 greedy test model (kv_restart_test.rs) with a |
| 104 | /// 16-token block and room for a 2048-token conversation. |
| 105 | pub fn model_config(block_size: usize, max_sequence_length: usize) -> ModelConfig { |
| 106 | ModelConfig { |
| 107 | model_id: "pkv-bench-reference".to_string(), |
| 108 | max_sequence_length, |
| 109 | block_size, |
| 110 | num_layers: 3, |
| 111 | num_heads: 4, |
| 112 | head_dim: 8, |
| 113 | num_kv_heads: 2, |
| 114 | hidden_dim: 32, |
| 115 | intermediate_dim: 64, |
| 116 | vocab_size: VOCAB as usize, |
| 117 | rms_norm_eps: 1e-5, |
| 118 | rope_theta: 10000.0, |
| 119 | rope_scaling: None, |
| 120 | tie_word_embeddings: false, |
| 121 | // Never emitted (above the vocabulary): every request runs to its |
| 122 | // max_tokens, so rows compare equal work (an empty list would use |
| 123 | // the legacy stop ids, which the reference weights do emit). |
| 124 | eos_token_ids: vec![NO_EOS], |
| 125 | qk_norm: false, |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | pub fn model_label() -> String { |
| 130 | let c = model_config(16, 0); |
| 131 | format!( |
| 132 | "reference test weights (TransformerWeights::reference_test_weights): {} layers, hidden {}, {} heads, {} kv heads, head_dim {}, vocab {}; synthetic, not a real model", |
| 133 | c.num_layers, c.hidden_dim, c.num_heads, c.num_kv_heads, c.head_dim, c.vocab_size |
| 134 | ) |
| 135 | } |
| 136 | |
| 137 | /// Deterministic prompt tokens, distinct per (round, conversation, salt). |
| 138 | fn tokens(seed: u64, len: usize) -> Vec<u32> { |
| 139 | let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0xD1B5_4A32_D192_ED03; |
| 140 | (0..len) |
| 141 | .map(|_| { |
| 142 | x ^= x << 13; |
| 143 | x ^= x >> 7; |
| 144 | x ^= x << 17; |
| 145 | (x % u64::from(VOCAB)) as u32 |
| 146 | }) |
| 147 | .collect() |
| 148 | } |
| 149 | |
| 150 | /// Peak RSS reset (Linux: writing 5 to clear_refs resets VmHWM for this |
| 151 | /// process; no privilege needed for our own process). |
| 152 | pub fn reset_peak_rss() -> Result<(), String> { |
| 153 | std::fs::write("/proc/self/clear_refs", "5").map_err(|e| format!("clear_refs: {e}")) |
| 154 | } |
| 155 | |
| 156 | pub fn peak_rss_bytes() -> Result<u64, String> { |
| 157 | let status = |
| 158 | std::fs::read_to_string("/proc/self/status").map_err(|e| format!("status: {e}"))?; |
| 159 | status |
| 160 | .lines() |
| 161 | .find_map(|l| l.strip_prefix("VmHWM:")) |
| 162 | .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok()) |
| 163 | .map(|kb| kb * 1024) |
| 164 | .ok_or_else(|| "no VmHWM in /proc/self/status".to_string()) |
| 165 | } |
| 166 | |
| 167 | struct Peaks { |
| 168 | holder_blocks: usize, |
| 169 | } |
| 170 | |
| 171 | struct Done { |
| 172 | latency_us: Vec<u64>, |
| 173 | ttft_us: Vec<u64>, |
| 174 | /// Generated tokens per prompt, in submission order (empty when failed). |
| 175 | tokens: Vec<Vec<u32>>, |
| 176 | failed: u64, |
| 177 | decode_tokens: u64, |
| 178 | decode_window: Duration, |
| 179 | } |
| 180 | |
| 181 | struct Bench { |
| 182 | spine: AienRuntimeSpine, |
| 183 | backend: NativeTransformerBackend, |
| 184 | rx: tokio::sync::mpsc::UnboundedReceiver<CompletionEvent>, |
| 185 | sink: aien_scheduler::CompletionSinkId, |
| 186 | block_stride: u64, |
| 187 | pool_bytes: u64, |
| 188 | /// `WorkerConfig.dispatch_depth` of the store, 0 without a store. |
| 189 | queue_depth: u32, |
| 190 | peaks: Peaks, |
| 191 | deadline: Instant, |
| 192 | } |
| 193 | |
| 194 | impl Bench { |
| 195 | fn sample(&mut self) { |
| 196 | if let Some(s) = self.spine.kv_residency_status() { |
| 197 | self.peaks.holder_blocks = self.peaks.holder_blocks.max(s.holder_blocks); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | async fn step(&mut self) -> Result<(), String> { |
| 202 | if Instant::now() > self.deadline { |
| 203 | return Err("row exceeded its time budget".into()); |
| 204 | } |
| 205 | self.spine.step(&mut self.backend).await?; |
| 206 | self.sample(); |
| 207 | Ok(()) |
| 208 | } |
| 209 | |
| 210 | /// Steps until no park job is in flight (outside any measured window). |
| 211 | async fn wait_parks(&mut self) -> Result<(), String> { |
| 212 | while self |
| 213 | .spine |
| 214 | .kv_residency_status() |
| 215 | .is_some_and(|s| s.parking_jobs > 0) |
| 216 | { |
| 217 | self.step().await?; |
| 218 | std::thread::sleep(Duration::from_micros(200)); |
| 219 | } |
| 220 | Ok(()) |
| 221 | } |
| 222 | |
| 223 | async fn wait_store_open(&mut self) -> Result<(), String> { |
| 224 | use aien_kv_store::StoreState; |
| 225 | loop { |
| 226 | let state = self.spine.kv_residency().map(|r| r.store_capacity().state); |
| 227 | match state { |
| 228 | None | Some(StoreState::Open) => return Ok(()), |
| 229 | Some(StoreState::Recovering) => { |
| 230 | self.step().await?; |
| 231 | std::thread::sleep(Duration::from_millis(1)); |
| 232 | } |
| 233 | Some(other) => return Err(format!("store did not open: {other:?}")), |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | /// Submits every prompt, steps until each has finished, and returns the |
| 239 | /// timings. Token times are taken when the channel is drained after a step. |
| 240 | async fn run_batch(&mut self, prompts: &[Vec<u32>], max_tokens: usize) -> Result<Done, String> { |
| 241 | let mut submitted: HashMap<u64, Instant> = HashMap::new(); |
| 242 | let mut order = Vec::new(); |
| 243 | for p in prompts { |
| 244 | let at = Instant::now(); |
| 245 | let seq = self.spine.submit_work( |
| 246 | Arc::from(p.clone()), |
| 247 | SamplingParams { |
| 248 | temperature: 0.0, |
| 249 | top_p: 1.0, |
| 250 | max_tokens, |
| 251 | stop_token_ids: vec![], |
| 252 | }, |
| 253 | 1, |
| 254 | Some(self.sink), |
| 255 | )?; |
| 256 | submitted.insert(seq, at); |
| 257 | order.push(seq); |
| 258 | } |
| 259 | let mut first: HashMap<u64, Instant> = HashMap::new(); |
| 260 | let mut finished: HashMap<u64, Instant> = HashMap::new(); |
| 261 | let mut tokens: HashMap<u64, Vec<u32>> = HashMap::new(); |
| 262 | let mut failed = 0u64; |
| 263 | while finished.len() + (failed as usize) < order.len() { |
| 264 | self.step().await?; |
| 265 | let now = Instant::now(); |
| 266 | while let Ok(ev) = self.rx.try_recv() { |
| 267 | match ev { |
| 268 | CompletionEvent::Token { seq_id, token } => { |
| 269 | let id = seq_id.to_u64(); |
| 270 | first.entry(id).or_insert(now); |
| 271 | tokens.entry(id).or_default().push(token); |
| 272 | } |
| 273 | CompletionEvent::Finished { seq_id, .. } => { |
| 274 | finished.insert(seq_id.to_u64(), now); |
| 275 | } |
| 276 | CompletionEvent::Error { seq_id, message } => { |
| 277 | eprintln!("request {} failed: {message}", seq_id.to_u64()); |
| 278 | failed += 1; |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | let mut done = Done { |
| 284 | latency_us: Vec::new(), |
| 285 | ttft_us: Vec::new(), |
| 286 | tokens: Vec::new(), |
| 287 | failed, |
| 288 | decode_tokens: 0, |
| 289 | decode_window: Duration::ZERO, |
| 290 | }; |
| 291 | let mut window_start: Option<Instant> = None; |
| 292 | let mut window_end: Option<Instant> = None; |
| 293 | for id in order { |
| 294 | let (Some(end), Some(t1)) = (finished.get(&id), first.get(&id)) else { |
| 295 | done.tokens.push(Vec::new()); |
| 296 | continue; |
| 297 | }; |
| 298 | let at = submitted[&id]; |
| 299 | let toks = tokens.remove(&id).unwrap_or_default(); |
| 300 | if toks.len() != max_tokens { |
| 301 | return Err(format!( |
| 302 | "request {id} produced {} tokens, expected {max_tokens}", |
| 303 | toks.len() |
| 304 | )); |
| 305 | } |
| 306 | done.latency_us |
| 307 | .push(end.duration_since(at).as_micros() as u64); |
| 308 | done.ttft_us.push(t1.duration_since(at).as_micros() as u64); |
| 309 | done.decode_tokens += toks.len().saturating_sub(1) as u64; |
| 310 | window_start = Some(window_start.map_or(*t1, |w| w.min(*t1))); |
| 311 | window_end = Some(window_end.map_or(*end, |w| w.max(*end))); |
| 312 | done.tokens.push(toks); |
| 313 | } |
| 314 | if let (Some(s), Some(e)) = (window_start, window_end) { |
| 315 | done.decode_window = e.duration_since(s); |
| 316 | } |
| 317 | Ok(done) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// Per-class store bounds (ADR 7.1) large enough that every chunk of every |
| 322 | /// conversation finishing in the same step is admitted: `c` times the chunks of |
| 323 | /// the longest turn plus one tail, never below the defaults (48 restore, 16 |
| 324 | /// park). With the defaults, 8 conversations of 512 tokens finishing together |
| 325 | /// submit 24 parks and 8 are refused `QueueFull` (by design: not parked this |
| 326 | /// turn), so their next turn prefills and the row could not be called a restore. |
| 327 | pub fn store_op_bounds(spec: &RunSpec, c: u32, turn_tokens: usize) -> (u32, u32) { |
| 328 | let defaults = aien_kv_store::worker::WorkerConfig::default(); |
| 329 | let chunk_tokens = spec.chunk_blocks as usize * spec.block_size; |
| 330 | let per_conv = turn_tokens.div_ceil(chunk_tokens.max(1)) as u32 + 1; |
| 331 | let need = c.saturating_mul(per_conv); |
| 332 | ( |
| 333 | need.max(defaults.max_restore_ops), |
| 334 | need.max(defaults.max_park_ops), |
| 335 | ) |
| 336 | } |
| 337 | |
| 338 | fn build(spec: &RunSpec, mode: Mode, c: u32, prompt: u32) -> Result<Bench, String> { |
| 339 | let turn2_len = |
| 340 | prompt as usize + spec.turn1_max_tokens + spec.turn2_suffix_tokens + spec.turn2_max_tokens; |
| 341 | let blocks_per_conv = turn2_len.div_ceil(spec.block_size) + 1; |
| 342 | let total_blocks = c as usize * blocks_per_conv * 3 + 64; |
| 343 | let config = model_config(spec.block_size, turn2_len + spec.block_size); |
| 344 | let weights = TransformerWeights::reference_test_weights(&config); |
| 345 | let (mut spine, backend) = build_shared_kv_runtime( |
| 346 | weights, |
| 347 | Arc::new(ReferenceCpuBackend::new()), |
| 348 | SchedulerConfig { |
| 349 | max_batch_size: 16, |
| 350 | max_batch_tokens: 4096, |
| 351 | max_prefill_tokens: 4096, |
| 352 | prefill_chunk_size: 4096, |
| 353 | chunk_prefill: true, |
| 354 | watermark_blocks: 0, |
| 355 | }, |
| 356 | SharedKvSizing { |
| 357 | arena_capacity: 4 * c as usize + 16, |
| 358 | total_blocks, |
| 359 | }, |
| 360 | )?; |
| 361 | let (block_stride, pool_bytes) = { |
| 362 | let guard = spine.kv_manager.read(); |
| 363 | let layout = guard |
| 364 | .pool() |
| 365 | .ok_or("runtime KV manager has no pool")? |
| 366 | .layout(); |
| 367 | (layout.block_stride_bytes as u64, layout.total_bytes as u64) |
| 368 | }; |
| 369 | let mut queue_depth = 0; |
| 370 | if mode.uses_store() { |
| 371 | let dir = spec |
| 372 | .store_root |
| 373 | .join(format!("{}-c{c}-p{prompt}", mode.label())); |
| 374 | if dir.exists() { |
| 375 | std::fs::remove_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; |
| 376 | } |
| 377 | // The host store refuses a root group or others can reach (ADR 0003 |
| 378 | // section 19), so the run directory is created 0700. |
| 379 | { |
| 380 | use std::os::unix::fs::DirBuilderExt; |
| 381 | std::fs::DirBuilder::new() |
| 382 | .recursive(true) |
| 383 | .mode(0o700) |
| 384 | .create(&dir) |
| 385 | .map_err(|e| format!("{}: {e}", dir.display()))?; |
| 386 | } |
| 387 | let dir_s = dir.to_string_lossy().to_string(); |
| 388 | let chunk = spec.chunk_blocks.to_string(); |
| 389 | let restore_max = total_blocks.to_string(); |
| 390 | let (restore_ops, park_ops) = store_op_bounds(spec, c, turn2_len); |
| 391 | let (restore_ops, park_ops) = (restore_ops.to_string(), park_ops.to_string()); |
| 392 | let mut settings = KvPersistSettings::from_lookup(|k| match k { |
| 393 | KV_STORE_DIR_ENV => Some(dir_s.clone()), |
| 394 | KV_CHUNK_BLOCKS_ENV => Some(chunk.clone()), |
| 395 | KV_RESTORE_MAX_BLOCKS_ENV => Some(restore_max.clone()), |
| 396 | "AIEN_KV_STORE_MAX_RESTORE_OPS" => Some(restore_ops.clone()), |
| 397 | "AIEN_KV_STORE_MAX_PARK_OPS" => Some(park_ops.clone()), |
| 398 | _ => None, |
| 399 | })?; |
| 400 | // A fresh random store key per run: objects are sealed as in the daemon |
| 401 | // (ADR 0003 section 20), so restore timings include decryption. |
| 402 | settings.store_key = Some(Ok(std::sync::Arc::new( |
| 403 | aien_kv_store::seal::SealKey::generate() |
| 404 | .map_err(|e| format!("bench store key: {e:?}"))?, |
| 405 | ))); |
| 406 | queue_depth = settings.worker.dispatch_depth; |
| 407 | let host_engine = aien_runtime::compute_config::HostEngineIdentity::reference( |
| 408 | ReferenceCpuBackend::new().name(), |
| 409 | ) |
| 410 | .map_err(|e| format!("engine identity: {e}"))?; |
| 411 | enable_persistent_kv( |
| 412 | &mut spine, |
| 413 | &settings, |
| 414 | &ModelKvBinding { |
| 415 | model: &config, |
| 416 | arith_id: ReferenceCpuBackend::new().name(), |
| 417 | // Synthetic weights have no file; a fixed digest names them. |
| 418 | model_sha256: [0xB9; 32], |
| 419 | model_digest_kind: "sha256", |
| 420 | engine: host_engine.identity(), |
| 421 | }, |
| 422 | None, |
| 423 | )? |
| 424 | .ok_or("persistence did not switch on")?; |
| 425 | } |
| 426 | let (sink, rx) = ChannelCompletionSink::channel(); |
| 427 | let sink = spine.register_completion_sink(Arc::new(sink)); |
| 428 | Ok(Bench { |
| 429 | spine, |
| 430 | backend, |
| 431 | rx, |
| 432 | sink, |
| 433 | block_stride, |
| 434 | pool_bytes, |
| 435 | queue_depth, |
| 436 | peaks: Peaks { holder_blocks: 0 }, |
| 437 | deadline: Instant::now() + Duration::from_secs(300), |
| 438 | }) |
| 439 | } |
| 440 | |
| 441 | /// Measures one (mode, concurrency, prompt length) row. |
| 442 | pub async fn run_row(spec: &RunSpec, mode: Mode, c: u32, prompt: u32) -> Result<Row, String> { |
| 443 | if mode == Mode::RestoreDevice { |
| 444 | return Err("restore-from-device is NOT_RUN by design".into()); |
| 445 | } |
| 446 | let workload = if mode == Mode::ResidentOnly { |
| 447 | "single_turn" |
| 448 | } else { |
| 449 | "second_turn" |
| 450 | }; |
| 451 | let mut b = build(spec, mode, c, prompt)?; |
| 452 | b.wait_store_open().await?; |
| 453 | reset_peak_rss()?; |
| 454 | let mut row = Row::new_ok( |
| 455 | mode.label(), |
| 456 | HOSTED, |
| 457 | mode.cache_state(), |
| 458 | c, |
| 459 | prompt, |
| 460 | workload, |
| 461 | ); |
| 462 | let mut failed = 0u64; |
| 463 | let mut decode_tokens = 0u64; |
| 464 | let mut decode_window = Duration::ZERO; |
| 465 | let mut restored = 0u64; |
| 466 | for round in 0..spec.rounds { |
| 467 | let prompts: Vec<Vec<u32>> = (0..c) |
| 468 | .map(|i| { |
| 469 | tokens( |
| 470 | u64::from(round) << 32 | u64::from(i) << 8 | u64::from(prompt % 251), |
| 471 | prompt as usize, |
| 472 | ) |
| 473 | }) |
| 474 | .collect(); |
| 475 | let measured = if mode == Mode::ResidentOnly { |
| 476 | b.run_batch(&prompts, spec.turn2_max_tokens).await? |
| 477 | } else { |
| 478 | let turn1 = b.run_batch(&prompts, spec.turn1_max_tokens).await?; |
| 479 | if turn1.failed > 0 { |
| 480 | return Err(format!("{} turn-1 requests failed", turn1.failed)); |
| 481 | } |
| 482 | b.wait_parks().await?; |
| 483 | let turn2: Vec<Vec<u32>> = prompts |
| 484 | .iter() |
| 485 | .enumerate() |
| 486 | .map(|(i, p)| { |
| 487 | let mut t = p.clone(); |
| 488 | t.extend(&turn1.tokens[i]); |
| 489 | t.extend(tokens( |
| 490 | 0xC9 << 40 | u64::from(round) << 16 | i as u64, |
| 491 | spec.turn2_suffix_tokens, |
| 492 | )); |
| 493 | t |
| 494 | }) |
| 495 | .collect(); |
| 496 | let before = b.spine.kv_residency_status().map(|s| s.stats); |
| 497 | let done = b.run_batch(&turn2, spec.turn2_max_tokens).await?; |
| 498 | let after = b.spine.kv_residency_status().map(|s| s.stats); |
| 499 | match (mode, before, after) { |
| 500 | (Mode::RestorePageCache, Some(before), Some(after)) => { |
| 501 | let committed = after.restore_committed_total - before.restore_committed_total; |
| 502 | if committed != u64::from(c) { |
| 503 | return Err(format!( |
| 504 | "round {round}: {committed} of {c} turn-2 requests committed a restore (fallbacks {}); refusing to label the row restore; before {:?} after {:?}", |
| 505 | after.restore_fallback_prefill_total |
| 506 | - before.restore_fallback_prefill_total, |
| 507 | before, |
| 508 | after |
| 509 | )); |
| 510 | } |
| 511 | restored += after.restore_tokens_total - before.restore_tokens_total; |
| 512 | } |
| 513 | (Mode::ColdPrefill, None, None) => {} |
| 514 | other => { |
| 515 | return Err(format!( |
| 516 | "residency state does not match the mode: {other:?}" |
| 517 | )) |
| 518 | } |
| 519 | } |
| 520 | done |
| 521 | }; |
| 522 | failed += measured.failed; |
| 523 | decode_tokens += measured.decode_tokens; |
| 524 | decode_window += measured.decode_window; |
| 525 | row.latency_samples_us.extend(&measured.latency_us); |
| 526 | row.ttft_samples_us.extend(&measured.ttft_us); |
| 527 | b.wait_parks().await?; |
| 528 | } |
| 529 | row.completed_requests = Some(row.latency_samples_us.len() as u64); |
| 530 | row.failed_requests = Some(failed); |
| 531 | row.decode_tokens_per_s = Some(if decode_window.is_zero() { |
| 532 | 0.0 |
| 533 | } else { |
| 534 | decode_tokens as f64 / decode_window.as_secs_f64() |
| 535 | }); |
| 536 | row.peak_allocated_bytes = Some(b.pool_bytes); |
| 537 | row.peak_holder_bytes = Some(b.peaks.holder_blocks as u64 * b.block_stride); |
| 538 | row.peak_staging_bytes = Some(if mode.uses_store() { b.block_stride } else { 0 }); |
| 539 | row.peak_rss_bytes = Some(peak_rss_bytes()?); |
| 540 | row.queue_depth = Some(b.queue_depth); |
| 541 | row.restored_tokens = Some(restored); |
| 542 | row.fill_percentiles(); |
| 543 | if let Some(drain) = b.spine.kv_drain_handle() { |
| 544 | let report = drain.drain(); |
| 545 | if !report.unfinished.is_empty() { |
| 546 | return Err(format!("store drain left {} jobs", report.unfinished.len())); |
| 547 | } |
| 548 | } |
| 549 | row.check().map_err(|e| e.to_string())?; |
| 550 | Ok(row) |
| 551 | } |