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-serve-http / src / qwen36_batch / tests.rs
| 1 | //! Host tests of the batch scheduler over a fake row model: every row's words equal the same |
| 2 | //! request alone, a row-state swap is caught, next turns reuse their row, cancel and stop work. |
| 3 | use super::*; |
| 4 | use aien_omega_q38::GraphStats; |
| 5 | use std::sync::atomic::AtomicUsize; |
| 6 | |
| 7 | const VOCAB: usize = 97; |
| 8 | |
| 9 | fn mix(mut z: u64) -> u64 { |
| 10 | z = z.wrapping_add(0x9e37_79b9_7f4a_7c15); |
| 11 | z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 12 | z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); |
| 13 | z ^ (z >> 31) |
| 14 | } |
| 15 | |
| 16 | /// A row model whose next token depends on every token fed so far and its position. |
| 17 | struct Fake { |
| 18 | rows: Vec<(u64, usize)>, |
| 19 | /// Swap two fed rows' states once, at the first step from this one on that feeds two rows |
| 20 | /// whose states differ (two rows seated this beat both hold the empty state, and swapping |
| 21 | /// equal states changes nothing). |
| 22 | swap_at: Option<u64>, |
| 23 | steps: u64, |
| 24 | fed: Arc<AtomicUsize>, |
| 25 | /// The rows each step fed, in order. |
| 26 | log: StepLog, |
| 27 | } |
| 28 | |
| 29 | impl Fake { |
| 30 | fn new(n: usize, swap_at: Option<u64>) -> (Self, Arc<AtomicUsize>) { |
| 31 | let fed = Arc::new(AtomicUsize::new(0)); |
| 32 | ( |
| 33 | Self { |
| 34 | rows: vec![(0, 0); n], |
| 35 | swap_at, |
| 36 | steps: 0, |
| 37 | fed: Arc::clone(&fed), |
| 38 | log: Arc::new(Mutex::new(Vec::new())), |
| 39 | }, |
| 40 | fed, |
| 41 | ) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl RowStep for Fake { |
| 46 | type Snap = (u64, usize); |
| 47 | fn row_snapshot(&mut self, r: usize, snap: &mut (u64, usize)) -> Result<(), String> { |
| 48 | *snap = self.rows[r]; |
| 49 | Ok(()) |
| 50 | } |
| 51 | fn row_restore(&mut self, r: usize, snap: &(u64, usize)) -> Result<(), String> { |
| 52 | self.rows[r] = *snap; |
| 53 | Ok(()) |
| 54 | } |
| 55 | fn row_count(&self) -> usize { |
| 56 | self.rows.len() |
| 57 | } |
| 58 | fn row_reset(&mut self, r: usize) -> Result<(), String> { |
| 59 | self.rows[r] = (0, 0); |
| 60 | Ok(()) |
| 61 | } |
| 62 | fn step_rows(&mut self, feed: &[RowFeed]) -> Result<Vec<RowOut>, String> { |
| 63 | self.steps += 1; |
| 64 | self.log |
| 65 | .lock() |
| 66 | .unwrap() |
| 67 | .push(feed.iter().map(|f| f.row).collect()); |
| 68 | // A step takes a moment, as on the chip, so requests started together overlap. |
| 69 | std::thread::sleep(Duration::from_micros(300)); |
| 70 | // As the chip's control: once, at the first step from k on that feeds two rows holding |
| 71 | // different states. |
| 72 | if self.swap_at.is_some_and(|k| self.steps >= k) { |
| 73 | let pair = (0..feed.len()) |
| 74 | .flat_map(|a| (a + 1..feed.len()).map(move |b| (a, b))) |
| 75 | .find(|&(a, b)| self.rows[feed[a].row] != self.rows[feed[b].row]); |
| 76 | if let Some((a, b)) = pair { |
| 77 | self.swap_at = None; |
| 78 | self.rows.swap(feed[a].row, feed[b].row); |
| 79 | } |
| 80 | } |
| 81 | let mut outs = Vec::new(); |
| 82 | for f in feed { |
| 83 | let (st, pos) = &mut self.rows[f.row]; |
| 84 | *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64); |
| 85 | *pos += 1; |
| 86 | self.fed.fetch_add(1, Ordering::SeqCst); |
| 87 | let logits: Vec<f32> = (0..VOCAB) |
| 88 | .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) |
| 89 | .collect(); |
| 90 | // The chip's argmax follows the host greedy rule. |
| 91 | let token = crate::sampling::sample_next(&logits, &greedy(1), 0); |
| 92 | outs.push(RowOut { |
| 93 | token, |
| 94 | logits: f.logits.then_some(logits), |
| 95 | stats: GraphStats::default(), |
| 96 | }); |
| 97 | } |
| 98 | Ok(outs) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | fn lock_file() -> PathBuf { |
| 103 | static N: AtomicUsize = AtomicUsize::new(0); |
| 104 | std::env::temp_dir().join(format!( |
| 105 | "l354-test-lock-{}-{}", |
| 106 | std::process::id(), |
| 107 | N.fetch_add(1, Ordering::SeqCst) |
| 108 | )) |
| 109 | } |
| 110 | |
| 111 | fn door(rows: usize, swap_at: Option<u64>, per_beat: usize) -> (Qwen36BatchDoor, Arc<AtomicUsize>) { |
| 112 | door_with(rows, swap_at, per_beat, true) |
| 113 | } |
| 114 | |
| 115 | fn door_with( |
| 116 | rows: usize, |
| 117 | swap_at: Option<u64>, |
| 118 | per_beat: usize, |
| 119 | chip_greedy: bool, |
| 120 | ) -> (Qwen36BatchDoor, Arc<AtomicUsize>) { |
| 121 | let (f, fed) = Fake::new(rows, swap_at); |
| 122 | let d = Qwen36BatchDoor::with_stepper( |
| 123 | f, |
| 124 | 4096, |
| 125 | lock_file(), |
| 126 | Duration::from_secs(5), |
| 127 | per_beat, |
| 128 | chip_greedy, |
| 129 | ) |
| 130 | .unwrap(); |
| 131 | (d, fed) |
| 132 | } |
| 133 | |
| 134 | fn greedy(n: usize) -> GenerateParams { |
| 135 | GenerateParams { |
| 136 | max_new_tokens: n, |
| 137 | temperature: 0.0, |
| 138 | top_p: 1.0, |
| 139 | top_k: 0, |
| 140 | seed: 0, |
| 141 | stop_token_ids: Vec::new(), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn run(d: &Qwen36BatchDoor, prompt: &[u32], p: &GenerateParams) -> (Vec<u32>, GenerateOutcome) { |
| 146 | let mut words = Vec::new(); |
| 147 | let o = d |
| 148 | .generate(prompt, p, &mut |t| { |
| 149 | words.push(t); |
| 150 | true |
| 151 | }) |
| 152 | .unwrap(); |
| 153 | (words, o) |
| 154 | } |
| 155 | |
| 156 | fn prompts() -> Vec<(Vec<u32>, usize)> { |
| 157 | (0..12u32) |
| 158 | .map(|i| { |
| 159 | let len = 1 + (i as usize * 7) % 40; |
| 160 | let p = (0..len as u32) |
| 161 | .map(|k| (k * 31 + i * 17 + 3) % VOCAB as u32) |
| 162 | .collect(); |
| 163 | (p, 5 + (i as usize * 11) % 26) |
| 164 | }) |
| 165 | .collect() |
| 166 | } |
| 167 | |
| 168 | fn alone(prompt: &[u32], n: usize) -> Vec<u32> { |
| 169 | let (d, _) = door(1, None, 1); |
| 170 | run(&d, prompt, &greedy(n)).0 |
| 171 | } |
| 172 | |
| 173 | /// Every prompt at once on `rows` rows (more prompts than rows queue for a free one), each |
| 174 | /// thread starting a little later than the one before: rows join and leave mid-spell. |
| 175 | fn concurrent(rows: usize, swap_at: Option<u64>, per_beat: usize) -> Vec<Vec<u32>> { |
| 176 | let (d, _) = door(rows, swap_at, per_beat); |
| 177 | let d = Arc::new(d); |
| 178 | let hs: Vec<_> = prompts() |
| 179 | .into_iter() |
| 180 | .enumerate() |
| 181 | .map(|(i, (p, n))| { |
| 182 | let d = Arc::clone(&d); |
| 183 | std::thread::spawn(move || { |
| 184 | std::thread::sleep(Duration::from_millis(i as u64 * 2)); |
| 185 | run(&d, &p, &greedy(n)).0 |
| 186 | }) |
| 187 | }) |
| 188 | .collect(); |
| 189 | hs.into_iter().map(|h| h.join().unwrap()).collect() |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn every_row_equals_the_request_alone() { |
| 194 | let want: Vec<Vec<u32>> = prompts().iter().map(|(p, n)| alone(p, *n)).collect(); |
| 195 | for (rows, per_beat) in [(1, 1), (4, 1), (4, 16), (8, 3), (12, 16)] { |
| 196 | let got = concurrent(rows, None, per_beat); |
| 197 | assert_eq!(got, want, "rows {rows}, prompt tokens per beat {per_beat}"); |
| 198 | } |
| 199 | for (w, (_, n)) in want.iter().zip(prompts()) { |
| 200 | assert_eq!(w.len(), n); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn row_swap_mutant_is_caught() { |
| 206 | let want: Vec<Vec<u32>> = prompts().iter().map(|(p, n)| alone(p, *n)).collect(); |
| 207 | let got = concurrent(12, Some(3), 1); |
| 208 | let differ = got.iter().zip(&want).filter(|(g, w)| g != w).count(); |
| 209 | assert!(differ >= 2, "the swap changed {differ} conversations"); |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn a_next_turn_continues_its_row() { |
| 214 | let (d, fed) = door(2, None, 4); |
| 215 | let p1: Vec<u32> = (0..20).map(|k| (k * 5 + 1) % VOCAB as u32).collect(); |
| 216 | let (r1, o1) = run(&d, &p1, &greedy(8)); |
| 217 | assert_eq!(o1.finish, FinishReason::Length); |
| 218 | // Turn 2 = turn 1's prompt, its reply, and a new question. |
| 219 | let mut p2 = p1.clone(); |
| 220 | p2.extend(&r1); |
| 221 | p2.extend([7, 8, 9]); |
| 222 | let before = fed.load(Ordering::SeqCst); |
| 223 | let (r2, _) = run(&d, &p2, &greedy(10)); |
| 224 | let tail = fed.load(Ordering::SeqCst) - before; |
| 225 | assert_eq!(r2, alone(&p2, 10), "reused row == cold row"); |
| 226 | // The row held p1 and r1 but its last token (never fed): 1 + 3 prompt tokens, 9 decoded. |
| 227 | assert_eq!(tail, 4 + 9); |
| 228 | // A prompt that does not continue any row's tokens goes in cold. |
| 229 | let p3: Vec<u32> = (0..6).map(|k| (k * 3 + 2) % VOCAB as u32).collect(); |
| 230 | let before = fed.load(Ordering::SeqCst); |
| 231 | let (r3, _) = run(&d, &p3, &greedy(3)); |
| 232 | assert_eq!(r3, alone(&p3, 3)); |
| 233 | assert_eq!(fed.load(Ordering::SeqCst) - before, 6 + 2); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn cancel_frees_the_row_and_stop_ends() { |
| 238 | let (d, _) = door(1, None, 1); |
| 239 | let p: Vec<u32> = vec![1, 2, 3]; |
| 240 | let mut got = Vec::new(); |
| 241 | let o = d |
| 242 | .generate(&p, &greedy(20), &mut |t| { |
| 243 | got.push(t); |
| 244 | got.len() < 3 |
| 245 | }) |
| 246 | .unwrap(); |
| 247 | assert_eq!(o.finish, FinishReason::Cancelled); |
| 248 | assert_eq!(o.emitted_tokens, 3); |
| 249 | let full = alone(&p, 20); |
| 250 | assert_eq!(got, full[..3]); |
| 251 | // The one row is free again; a stop token ends the reply before it. |
| 252 | let mut stop = greedy(20); |
| 253 | stop.stop_token_ids = vec![full[5]]; |
| 254 | let first = full.iter().position(|&t| t == full[5]).unwrap(); |
| 255 | let (w, o) = run(&d, &p, &stop); |
| 256 | assert_eq!(o.finish, FinishReason::Stop); |
| 257 | assert_eq!(w, full[..first]); |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn a_reworded_next_turn_restores_the_turn_header_copy() { |
| 262 | let (d, fed) = door(1, None, 4); |
| 263 | let im = IM_START; |
| 264 | let p1 = vec![1, 2, 3, im, 5, 6]; |
| 265 | let (r1, _) = run(&d, &p1, &greedy(4)); |
| 266 | // Turn 2 renders turn 1's reply differently (so the live tokens do not match) but keeps |
| 267 | // everything before turn 1's header: the copy taken there is restored. |
| 268 | let other = (r1[0] + 1) % VOCAB as u32; |
| 269 | let p2 = vec![1, 2, 3, im, 5, 6, other, 78, im, 4]; |
| 270 | let before = fed.load(Ordering::SeqCst); |
| 271 | let (r2, _) = run(&d, &p2, &greedy(5)); |
| 272 | assert_eq!(r2, alone(&p2, 5), "restored row == cold row"); |
| 273 | assert_eq!(fed.load(Ordering::SeqCst) - before, 7 + 4); |
| 274 | // Turn 3 continues turn 2 live: its copy (taken at p2's last header) is shorter than the live |
| 275 | // tokens, so the live state wins. |
| 276 | let mut p3 = p2.clone(); |
| 277 | p3.extend(&r2); |
| 278 | p3.extend([im, 9]); |
| 279 | let before = fed.load(Ordering::SeqCst); |
| 280 | let (r3, _) = run(&d, &p3, &greedy(2)); |
| 281 | assert_eq!(r3, alone(&p3, 2)); |
| 282 | assert_eq!(fed.load(Ordering::SeqCst) - before, 3 + 1); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn the_graphs_greedy_token_equals_the_host_argmax_path() { |
| 287 | let want: Vec<Vec<u32>> = prompts() |
| 288 | .iter() |
| 289 | .map(|(p, n)| { |
| 290 | let (d, _) = door_with(1, None, 1, false); |
| 291 | run(&d, p, &greedy(*n)).0 |
| 292 | }) |
| 293 | .collect(); |
| 294 | assert_eq!(concurrent(8, None, 16), want); |
| 295 | } |
| 296 | |
| 297 | // ---- the merge train's per-request switches (L384) ---- |
| 298 | |
| 299 | /// The fake honors the switches as the chip does: a mutant changes the row's own words and no |
| 300 | /// other row's; strokes and the exact head leave the words alone (the chip's contract for them). |
| 301 | impl Fake { |
| 302 | fn step_rows_switched(&mut self, feed: &[RowFeed], tests: &[RowTest]) -> Vec<RowOut> { |
| 303 | let mut outs = Vec::new(); |
| 304 | for (i, f) in feed.iter().enumerate() { |
| 305 | let t = tests.get(i).copied().unwrap_or_default(); |
| 306 | let (st, pos) = &mut self.rows[f.row]; |
| 307 | *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64); |
| 308 | if t.mutant != 0 { |
| 309 | *st = mix(*st ^ 0xdead_0000 ^ t.mutant as u64); |
| 310 | } |
| 311 | *pos += 1; |
| 312 | self.fed.fetch_add(1, Ordering::SeqCst); |
| 313 | let logits: Vec<f32> = (0..VOCAB) |
| 314 | .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) |
| 315 | .collect(); |
| 316 | let token = crate::sampling::sample_next(&logits, &greedy(1), 0); |
| 317 | outs.push(RowOut { |
| 318 | token, |
| 319 | logits: f.logits.then_some(logits), |
| 320 | stats: GraphStats::default(), |
| 321 | }); |
| 322 | } |
| 323 | outs |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// A fake whose `step_rows_test` applies the switches (the chip's `Qwen38Omega` does). |
| 328 | struct SwitchedFake(Fake); |
| 329 | |
| 330 | impl RowStep for SwitchedFake { |
| 331 | type Snap = (u64, usize); |
| 332 | fn row_snapshot(&mut self, r: usize, snap: &mut (u64, usize)) -> Result<(), String> { |
| 333 | self.0.row_snapshot(r, snap) |
| 334 | } |
| 335 | fn row_restore(&mut self, r: usize, snap: &(u64, usize)) -> Result<(), String> { |
| 336 | self.0.row_restore(r, snap) |
| 337 | } |
| 338 | fn row_count(&self) -> usize { |
| 339 | self.0.row_count() |
| 340 | } |
| 341 | fn row_reset(&mut self, r: usize) -> Result<(), String> { |
| 342 | self.0.row_reset(r) |
| 343 | } |
| 344 | fn step_rows(&mut self, feed: &[RowFeed]) -> Result<Vec<RowOut>, String> { |
| 345 | self.0.step_rows(feed) |
| 346 | } |
| 347 | fn step_rows_test( |
| 348 | &mut self, |
| 349 | feed: &[RowFeed], |
| 350 | tests: &[RowTest], |
| 351 | ) -> Result<Vec<RowOut>, String> { |
| 352 | self.0.steps += 1; |
| 353 | std::thread::sleep(Duration::from_micros(300)); |
| 354 | Ok(self.0.step_rows_switched(feed, tests)) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | fn switched_door(rows: usize) -> Qwen36BatchDoor { |
| 359 | let (f, _) = Fake::new(rows, None); |
| 360 | Qwen36BatchDoor::with_stepper( |
| 361 | SwitchedFake(f), |
| 362 | 4096, |
| 363 | lock_file(), |
| 364 | Duration::from_secs(5), |
| 365 | 4, |
| 366 | true, |
| 367 | ) |
| 368 | .unwrap() |
| 369 | } |
| 370 | |
| 371 | fn run_test(d: &Qwen36BatchDoor, prompt: &[u32], n: usize, t: TestSwitches) -> Vec<u32> { |
| 372 | let mut words = Vec::new(); |
| 373 | d.generate_test(prompt, &greedy(n), t, &mut |tok| { |
| 374 | words.push(tok); |
| 375 | true |
| 376 | }) |
| 377 | .unwrap(); |
| 378 | words |
| 379 | } |
| 380 | |
| 381 | /// Every prompt at once on one door; prompt `i` carries `switch(i)`. |
| 382 | fn concurrent_switched( |
| 383 | rows: usize, |
| 384 | switch: impl Fn(usize) -> TestSwitches + Send + Sync + 'static, |
| 385 | ) -> Vec<Vec<u32>> { |
| 386 | let d = Arc::new(switched_door(rows)); |
| 387 | let switch = Arc::new(switch); |
| 388 | let hs: Vec<_> = prompts() |
| 389 | .into_iter() |
| 390 | .enumerate() |
| 391 | .map(|(i, (p, n))| { |
| 392 | let (d, switch) = (Arc::clone(&d), Arc::clone(&switch)); |
| 393 | std::thread::spawn(move || { |
| 394 | std::thread::sleep(Duration::from_millis(i as u64 * 2)); |
| 395 | run_test(&d, &p, n, switch(i)) |
| 396 | }) |
| 397 | }) |
| 398 | .collect(); |
| 399 | hs.into_iter().map(|h| h.join().unwrap()).collect() |
| 400 | } |
| 401 | |
| 402 | #[test] |
| 403 | fn a_mutant_switch_changes_only_its_own_row() { |
| 404 | let want: Vec<Vec<u32>> = prompts().iter().map(|(p, n)| alone(p, *n)).collect(); |
| 405 | let got = concurrent_switched(4, |i| TestSwitches { |
| 406 | mutant: (i == 5).then_some(4), |
| 407 | ..TestSwitches::default() |
| 408 | }); |
| 409 | for (i, (g, w)) in got.iter().zip(&want).enumerate() { |
| 410 | if i == 5 { |
| 411 | assert_ne!(g, w, "the mutant row must go red"); |
| 412 | } else { |
| 413 | assert_eq!( |
| 414 | g, w, |
| 415 | "prompt {i} rode beside the mutant and must not change" |
| 416 | ); |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn a_negative_control_leaves_no_state_for_a_later_request() { |
| 423 | // L387 (train run 20261022T0119Z, row-swap-red): the mutant row's copy at its last turn |
| 424 | // header was kept, and the next request with the same prompt restored it and went red. |
| 425 | let mut p: Vec<u32> = (0..12u32).map(|k| 1 + (k * 13) % 90).collect(); |
| 426 | p.push(IM_START); |
| 427 | p.extend((0..6u32).map(|k| 2 + (k * 7) % 90)); |
| 428 | let want = alone(&p, 6); |
| 429 | let d = switched_door(1); |
| 430 | let red = run_test( |
| 431 | &d, |
| 432 | &p, |
| 433 | 6, |
| 434 | TestSwitches { |
| 435 | mutant: Some(4), |
| 436 | ..TestSwitches::default() |
| 437 | }, |
| 438 | ); |
| 439 | assert_ne!(red, want, "the mutant must go red"); |
| 440 | assert_eq!( |
| 441 | run_test(&d, &p, 6, TestSwitches::default()), |
| 442 | want, |
| 443 | "a plain request after a mutant must not reuse the mutant's state" |
| 444 | ); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn strokes_off_and_exact_head_off_equal_the_served_path() { |
| 449 | let want: Vec<Vec<u32>> = prompts().iter().map(|(p, n)| alone(p, *n)).collect(); |
| 450 | let got = concurrent_switched(8, |i| TestSwitches { |
| 451 | stroke: Some(i % 2 == 0), |
| 452 | exact_head: Some(i % 3 != 0), |
| 453 | ..TestSwitches::default() |
| 454 | }); |
| 455 | assert_eq!(got, want); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn a_row_swap_switch_trades_two_conversations_and_both_go_red() { |
| 460 | let want: Vec<Vec<u32>> = prompts().iter().map(|(p, n)| alone(p, *n)).collect(); |
| 461 | let got = concurrent_switched(12, |i| TestSwitches { |
| 462 | row_swap: (i == 3).then_some(2), |
| 463 | ..TestSwitches::default() |
| 464 | }); |
| 465 | let differ: Vec<usize> = got |
| 466 | .iter() |
| 467 | .zip(&want) |
| 468 | .enumerate() |
| 469 | .filter(|(_, (g, w))| g != w) |
| 470 | .map(|(i, _)| i) |
| 471 | .collect(); |
| 472 | assert!( |
| 473 | differ.contains(&3), |
| 474 | "the swapping conversation must go red: {differ:?}" |
| 475 | ); |
| 476 | assert!(differ.len() >= 2, "its partner must go red too: {differ:?}"); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn no_switches_is_the_served_path_on_a_stepper_without_them() { |
| 481 | // The plain `Fake` refuses `step_rows_test` with a switch: a request without switches never |
| 482 | // reaches it, and a request with one fails loudly instead of being served as plain. |
| 483 | let (d, _) = door(2, None, 4); |
| 484 | let p: Vec<u32> = vec![1, 2, 3, 4]; |
| 485 | assert_eq!(run_test(&d, &p, 5, TestSwitches::default()), alone(&p, 5)); |
| 486 | let r = d.generate_test( |
| 487 | &p, |
| 488 | &greedy(5), |
| 489 | TestSwitches { |
| 490 | mutant: Some(4), |
| 491 | ..TestSwitches::default() |
| 492 | }, |
| 493 | &mut |_| true, |
| 494 | ); |
| 495 | assert!(matches!(r, Err(EngineError::Failed(_))), "{r:?}"); |
| 496 | } |
| 497 | |
| 498 | #[test] |
| 499 | fn the_switch_names_round_trip_from_json() { |
| 500 | let t = TestSwitches::from_json(&serde_json::json!({ |
| 501 | "stroke": false, "exact_head": true, "mutant": 4, "row_swap": 7, |
| 502 | "prefill_chunk": 128, "prefix_pool": false, "state_bf16": null |
| 503 | })) |
| 504 | .unwrap(); |
| 505 | assert_eq!( |
| 506 | t.names(), |
| 507 | [ |
| 508 | "stroke", |
| 509 | "exact_head", |
| 510 | "mutant", |
| 511 | "row_swap", |
| 512 | "prefill_chunk", |
| 513 | "prefix_pool" |
| 514 | ] |
| 515 | ); |
| 516 | assert!(TestSwitches::from_json(&serde_json::json!({"strokes": true})).is_err()); |
| 517 | assert!(TestSwitches::from_json(&serde_json::json!({"mutant": "4"})).is_err()); |
| 518 | assert!(TestSwitches::from_json(&serde_json::json!({"mutant": 99})).is_err()); |
| 519 | assert!(TestSwitches::from_json(&serde_json::json!([])).is_err()); |
| 520 | assert!(TestSwitches::from_json(&serde_json::json!({})) |
| 521 | .unwrap() |
| 522 | .is_empty()); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn long_prompts_go_in_as_chunks_and_keep_the_turn_header_copy() { |
| 527 | // L369: a row with more than Q36_PREFILL_MIN prompt tokens left reads a chunk per beat |
| 528 | // (prefill_row); the replies are the request's alone, and a chunk stops at the last turn |
| 529 | // header, so the copy there is taken and a reworded next turn restores it. |
| 530 | let im = IM_START; |
| 531 | let body = |seed: u32, n: u32| -> Vec<u32> { |
| 532 | (0..n) |
| 533 | .map(|i| 1 + (seed.wrapping_mul(7919) ^ i.wrapping_mul(31)) % 90) |
| 534 | .collect() |
| 535 | }; |
| 536 | let mut p1 = body(1, 300); |
| 537 | p1.push(im); |
| 538 | p1.extend(body(2, 40)); |
| 539 | let (d, fed) = door(2, None, 4); |
| 540 | let (r1, _) = run(&d, &p1, &greedy(4)); |
| 541 | assert_eq!(r1, alone(&p1, 4)); |
| 542 | let other = (r1[0] + 1) % VOCAB as u32; |
| 543 | let mut p2 = p1.clone(); |
| 544 | p2.extend([other, 78, im]); |
| 545 | p2.extend(body(3, 150)); |
| 546 | let before = fed.load(Ordering::SeqCst); |
| 547 | let (r2, _) = run(&d, &p2, &greedy(5)); |
| 548 | assert_eq!(r2, alone(&p2, 5), "restored row == cold row"); |
| 549 | assert_eq!(fed.load(Ordering::SeqCst) - before, (p2.len() - 300) + 4); |
| 550 | } |
| 551 | |
| 552 | type StepLog = Arc<Mutex<Vec<Vec<usize>>>>; |
| 553 | |
| 554 | /// A door whose fake logs the rows of every step. |
| 555 | fn logged_door(rows: usize) -> (Arc<Qwen36BatchDoor>, StepLog) { |
| 556 | let (f, _) = Fake::new(rows, None); |
| 557 | let log = Arc::clone(&f.log); |
| 558 | let d = Qwen36BatchDoor::with_stepper(f, 4096, lock_file(), Duration::from_secs(5), 1, true) |
| 559 | .unwrap(); |
| 560 | (Arc::new(d), log) |
| 561 | } |
| 562 | |
| 563 | /// Eight short prompts (under `Q36_PREFILL_MIN`, so every token goes in through `step_rows` and a |
| 564 | /// beat is one logged step). |
| 565 | fn group_jobs() -> Vec<GroupJob> { |
| 566 | prompts() |
| 567 | .into_iter() |
| 568 | .take(8) |
| 569 | .map(|(mut p, n)| GroupJob { |
| 570 | prompt: { |
| 571 | p.truncate(Q36_PREFILL_MIN - 1); |
| 572 | p |
| 573 | }, |
| 574 | params: greedy(n), |
| 575 | cancel: None, |
| 576 | test: TestSwitches::default(), |
| 577 | }) |
| 578 | .collect() |
| 579 | } |
| 580 | |
| 581 | fn run_group(d: &Qwen36BatchDoor, jobs: &[GroupJob]) -> Vec<Vec<u32>> { |
| 582 | let mut words = vec![Vec::new(); jobs.len()]; |
| 583 | // Through the trait object, as the server calls it (an inherent method of the same name would |
| 584 | // shadow a missing trait override). |
| 585 | let outs = (d as &dyn Engine).generate_group(jobs, &mut |i, t| { |
| 586 | words[i].push(t); |
| 587 | true |
| 588 | }); |
| 589 | for o in &outs { |
| 590 | assert!(o.is_ok(), "{o:?}"); |
| 591 | } |
| 592 | words |
| 593 | } |
| 594 | |
| 595 | /// The readers' group (sc L371): eight jobs seated in one beat, beside a conversation already |
| 596 | /// running, each job's words those of the same request alone, in job order. |
| 597 | #[test] |
| 598 | fn a_group_of_eight_joins_in_one_beat_and_keeps_its_order() { |
| 599 | let (d, log) = logged_door(10); |
| 600 | let solo: Vec<u32> = (0..6).collect(); |
| 601 | let h = { |
| 602 | let d = Arc::clone(&d); |
| 603 | let solo = solo.clone(); |
| 604 | std::thread::spawn(move || run(&d, &solo, &greedy(300)).0) |
| 605 | }; |
| 606 | while log.lock().unwrap().len() < 5 { |
| 607 | std::thread::sleep(Duration::from_millis(1)); |
| 608 | } |
| 609 | let jobs = group_jobs(); |
| 610 | let got = run_group(&d, &jobs); |
| 611 | let want: Vec<Vec<u32>> = jobs |
| 612 | .iter() |
| 613 | .map(|j| alone(&j.prompt, j.params.max_new_tokens)) |
| 614 | .collect(); |
| 615 | assert_eq!(got, want); |
| 616 | assert_eq!(h.join().unwrap(), alone(&solo, 300)); |
| 617 | // Before the group one row steps; the first step with more has all nine. |
| 618 | let log = log.lock().unwrap(); |
| 619 | let first = log |
| 620 | .iter() |
| 621 | .position(|s| s.len() > 1) |
| 622 | .expect("the group stepped"); |
| 623 | assert!(first >= 5); |
| 624 | assert_eq!(log[first].len(), 9, "step {first}: {:?}", log[first]); |
| 625 | } |
| 626 | |
| 627 | /// A group waits for enough free rows and nothing seats a part of it early. |
| 628 | #[test] |
| 629 | fn a_group_waits_for_its_rows_then_joins_whole() { |
| 630 | let (d, log) = logged_door(8); |
| 631 | let solo: Vec<u32> = (0..4).collect(); |
| 632 | let h = { |
| 633 | let d = Arc::clone(&d); |
| 634 | std::thread::spawn(move || run(&d, &solo, &greedy(40)).0) |
| 635 | }; |
| 636 | while log.lock().unwrap().is_empty() { |
| 637 | std::thread::sleep(Duration::from_millis(1)); |
| 638 | } |
| 639 | let got = run_group(&d, &group_jobs()); |
| 640 | h.join().unwrap(); |
| 641 | assert_eq!(got.len(), 8); |
| 642 | let log = log.lock().unwrap(); |
| 643 | // One row (the single conversation) until it leaves, then all eight at once. |
| 644 | let first = log |
| 645 | .iter() |
| 646 | .position(|s| s.len() > 1) |
| 647 | .expect("the group stepped"); |
| 648 | assert!(log[..first].iter().all(|s| s.len() == 1)); |
| 649 | assert_eq!(log[first].len(), 8); |
| 650 | assert!( |
| 651 | first >= 40, |
| 652 | "the group started before the single left (step {first})" |
| 653 | ); |
| 654 | } |
| 655 | |
| 656 | #[test] |
| 657 | fn a_group_larger_than_the_door_is_refused_whole() { |
| 658 | let (d, _) = door(4, None, 1); |
| 659 | let outs = d.generate_group(&group_jobs(), &mut |_, _| true); |
| 660 | assert_eq!(outs.len(), 8); |
| 661 | assert!(outs |
| 662 | .iter() |
| 663 | .all(|o| matches!(o, Err(EngineError::Failed(m)) if m.contains("needs 8 rows")))); |
| 664 | } |
| 665 | |
| 666 | /// The caller's flag stops a job still taking in its prompt (the readers' client left). |
| 667 | #[test] |
| 668 | fn a_group_job_stops_on_the_callers_flag_while_prefilling() { |
| 669 | let (d, _) = door(8, None, 1); |
| 670 | let flag = Arc::new(AtomicBool::new(true)); |
| 671 | let jobs: Vec<GroupJob> = group_jobs() |
| 672 | .into_iter() |
| 673 | .map(|mut j| { |
| 674 | j.cancel = Some(Arc::clone(&flag)); |
| 675 | j |
| 676 | }) |
| 677 | .collect(); |
| 678 | let outs = d.generate_group(&jobs, &mut |_, _| true); |
| 679 | for o in outs { |
| 680 | let o = o.unwrap(); |
| 681 | assert_eq!(o.finish, FinishReason::Cancelled); |
| 682 | assert_eq!(o.emitted_tokens, 0); |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | /// Records the lock's release, for the load admission order. |
| 687 | struct Release<'a>(&'a std::cell::RefCell<Vec<&'static str>>); |
| 688 | |
| 689 | impl Drop for Release<'_> { |
| 690 | fn drop(&mut self) { |
| 691 | self.0.borrow_mut().push("release"); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | const LOAD_NEED: u64 = 30 << 30; |
| 696 | const LOAD_KEEP: u64 = 8 << 30; |
| 697 | |
| 698 | /// The load reads free memory only once the chip lock is ours (the wait can last up to |
| 699 | /// `LOAD_LOCK_WAIT`, and free memory on a shared box swings by tens of GiB meanwhile), and |
| 700 | /// uploads only after that reading admitted it. |
| 701 | #[test] |
| 702 | fn load_reads_memory_after_the_lock_and_before_the_upload() { |
| 703 | let log = std::cell::RefCell::new(Vec::new()); |
| 704 | let (lock, avail) = admit_then_open( |
| 705 | || { |
| 706 | log.borrow_mut().push("lock"); |
| 707 | Ok(Release(&log)) |
| 708 | }, |
| 709 | || { |
| 710 | log.borrow_mut().push("memory"); |
| 711 | LOAD_NEED + LOAD_KEEP |
| 712 | }, |
| 713 | LOAD_NEED, |
| 714 | LOAD_KEEP, |
| 715 | |avail| { |
| 716 | log.borrow_mut().push("open"); |
| 717 | Ok(avail) |
| 718 | }, |
| 719 | ) |
| 720 | .expect("exactly need plus keep-free is enough"); |
| 721 | assert_eq!(avail, LOAD_NEED + LOAD_KEEP); |
| 722 | drop(lock); |
| 723 | assert_eq!(*log.borrow(), ["lock", "memory", "open", "release"]); |
| 724 | } |
| 725 | |
| 726 | /// 59 GiB free before the wait, 6 GiB after it: the reading after the lock refuses, the lock is |
| 727 | /// let go and nothing is uploaded. |
| 728 | #[test] |
| 729 | fn load_refused_after_the_wait_releases_the_lock_and_uploads_nothing() { |
| 730 | let log = std::cell::RefCell::new(Vec::new()); |
| 731 | let e = admit_then_open( |
| 732 | || { |
| 733 | log.borrow_mut().push("lock"); |
| 734 | Ok(Release(&log)) |
| 735 | }, |
| 736 | || { |
| 737 | log.borrow_mut().push("memory"); |
| 738 | 6 << 30 |
| 739 | }, |
| 740 | LOAD_NEED, |
| 741 | LOAD_KEEP, |
| 742 | |_| -> Result<(), String> { |
| 743 | log.borrow_mut().push("open"); |
| 744 | Ok(()) |
| 745 | }, |
| 746 | ) |
| 747 | .err() |
| 748 | .expect("6 GiB is refused"); |
| 749 | assert!( |
| 750 | e.contains("MemAvailable 6144 MiB after taking the GPU lock"), |
| 751 | "{e}" |
| 752 | ); |
| 753 | assert_eq!(*log.borrow(), ["lock", "memory", "release"]); |
| 754 | } |
| 755 | |
| 756 | #[test] |
| 757 | fn load_without_the_lock_reads_no_memory_and_uploads_nothing() { |
| 758 | let r: Result<((), ()), String> = admit_then_open( |
| 759 | || Err("lock wait timed out".into()), |
| 760 | || panic!("memory must not be read without the lock"), |
| 761 | LOAD_NEED, |
| 762 | LOAD_KEEP, |
| 763 | |_| panic!("nothing is uploaded without the lock"), |
| 764 | ); |
| 765 | assert_eq!(r.unwrap_err(), "lock wait timed out"); |
| 766 | } |
| 767 | |
| 768 | /// A reader that stops taking its events (its request thread blocked, as a streaming reply's |
| 769 | /// `blocking_send` blocks when the client stops reading) must not stall the scheduler, which |
| 770 | /// holds the chip lock: once the reader's event channel is full its row is dropped, the other |
| 771 | /// conversation finishes exactly as alone, the lock is let go when the spell ends, and the |
| 772 | /// stalled request ends with an error that says why. |
| 773 | #[test] |
| 774 | fn a_reader_that_stops_reading_is_dropped_and_the_others_finish() { |
| 775 | use std::os::fd::AsRawFd; |
| 776 | let (f, _) = Fake::new(2, None); |
| 777 | let lock = lock_file(); |
| 778 | let d = Arc::new( |
| 779 | Qwen36BatchDoor::with_stepper(f, 4096, lock.clone(), Duration::from_secs(5), 1, true) |
| 780 | .unwrap(), |
| 781 | ); |
| 782 | let (release, hold) = mpsc::channel::<()>(); |
| 783 | let stalled = { |
| 784 | let d = Arc::clone(&d); |
| 785 | std::thread::spawn(move || { |
| 786 | let mut first = true; |
| 787 | d.generate(&[1, 2, 3], &greedy(2000), &mut |_| { |
| 788 | if std::mem::take(&mut first) { |
| 789 | // Stops reading after its first token, until the test lets go. |
| 790 | let _ = hold.recv(); |
| 791 | } |
| 792 | true |
| 793 | }) |
| 794 | }) |
| 795 | }; |
| 796 | // The other conversation joins before the stalled reader's channel fills (256 events, some |
| 797 | // 80 ms of fake steps) and is long enough to be mid-reply when it does. |
| 798 | std::thread::sleep(Duration::from_millis(10)); |
| 799 | let other: Vec<u32> = (0..6).collect(); |
| 800 | let (done_tx, done_rx) = mpsc::channel(); |
| 801 | { |
| 802 | let d = Arc::clone(&d); |
| 803 | let other = other.clone(); |
| 804 | std::thread::spawn(move || { |
| 805 | let _ = done_tx.send(run(&d, &other, &greedy(1000)).0); |
| 806 | }); |
| 807 | } |
| 808 | let got = done_rx |
| 809 | .recv_timeout(Duration::from_secs(30)) |
| 810 | .expect("the other conversation must finish while a reader is stalled"); |
| 811 | assert_eq!(got, alone(&other, 1000)); |
| 812 | let file = std::fs::OpenOptions::new() |
| 813 | .read(true) |
| 814 | .write(true) |
| 815 | .open(&lock) |
| 816 | .unwrap(); |
| 817 | let t = Instant::now(); |
| 818 | // SAFETY: flock on a valid descriptor of the test's private lock file. |
| 819 | while unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { |
| 820 | assert!( |
| 821 | t.elapsed() < Duration::from_secs(30), |
| 822 | "the scheduler still holds the chip lock" |
| 823 | ); |
| 824 | std::thread::sleep(Duration::from_millis(10)); |
| 825 | } |
| 826 | drop(file); |
| 827 | release.send(()).unwrap(); |
| 828 | match stalled.join().unwrap() { |
| 829 | Err(EngineError::Failed(m)) => assert!(m.contains("fell behind"), "{m}"), |
| 830 | r => panic!("the stalled reader's request: {r:?}"), |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | /// The interleaving the stall test cannot force: the reader falls behind (an event is dropped and |
| 835 | /// the scheduler cancels the job), then resumes and drains before the scheduler sends the job's |
| 836 | /// last event, so `Done` fits. The request must still fail as fallen behind, not report a normal |
| 837 | /// completion of a truncated reply, and only the delivered tokens reach the caller. |
| 838 | #[test] |
| 839 | fn a_reader_that_fell_behind_fails_even_when_its_done_fits() { |
| 840 | let (otx, orx) = mpsc::sync_channel::<(usize, Ev)>(2); |
| 841 | let cancel = Arc::new(AtomicBool::new(false)); |
| 842 | let fell = Arc::new(AtomicBool::new(false)); |
| 843 | let job = Job { |
| 844 | prompt: vec![1, 2, 3], |
| 845 | params: greedy(10), |
| 846 | out: otx, |
| 847 | tag: 0, |
| 848 | cancel: Arc::clone(&cancel), |
| 849 | fell_behind: Arc::clone(&fell), |
| 850 | t_queued: Instant::now(), |
| 851 | test: TestSwitches::default(), |
| 852 | }; |
| 853 | assert!(job.send(Ev::Token(11)).is_ok()); |
| 854 | assert!(job.send(Ev::Token(12)).is_ok()); |
| 855 | assert!(job.send(Ev::Token(13)).is_err(), "the channel is full"); |
| 856 | assert!( |
| 857 | cancel.load(Ordering::SeqCst), |
| 858 | "the scheduler cancels the job" |
| 859 | ); |
| 860 | let (drained_tx, drained_rx) = mpsc::channel(); |
| 861 | let consumer = std::thread::spawn(move || { |
| 862 | let mut got = Vec::new(); |
| 863 | let r = relay(&orx, &[cancel], &[fell], &mut |_, t| { |
| 864 | got.push(t); |
| 865 | if got.len() == 2 { |
| 866 | let _ = drained_tx.send(()); |
| 867 | } |
| 868 | true |
| 869 | }); |
| 870 | (r, got) |
| 871 | }); |
| 872 | // The reader has taken both queued tokens: the job's last event fits now. |
| 873 | drained_rx.recv().unwrap(); |
| 874 | job.send(Ev::Done(GenerateOutcome { |
| 875 | emitted_tokens: 3, |
| 876 | finish: FinishReason::Cancelled, |
| 877 | prefill_ms: 0, |
| 878 | decode_ms: 0, |
| 879 | sampling: None, |
| 880 | })) |
| 881 | .expect("Done fits after the drain"); |
| 882 | drop(job); |
| 883 | let (mut r, got) = consumer.join().unwrap(); |
| 884 | assert_eq!(got, [11, 12]); |
| 885 | match r.pop().expect("one outcome") { |
| 886 | Err(EngineError::Failed(m)) => assert!(m.contains("fell behind"), "{m}"), |
| 887 | other => panic!("a truncated reply reported as {other:?}"), |
| 888 | } |
| 889 | } |