Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/generation/tests.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / generation / tests.rs` 1147 lines ยท 39394 bytes Raw Blame History 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 //! ADR 0004 section 5: the forward-pass contract suite and the generation controller's tests, 17 //! run on the host fake `EchoChainModel`. Every sharpness test compares a run of at least 8 18 //! tokens (a chance agreement of 8 tokens is about 1 in 64^8). 19 20 use super::echo_chain::{echo_geometry, Call, CorruptRowKv, EchoChainModel, EchoKv, ECHO_VOCAB}; 21 use super::*; 22 use crate::qwen3_moe_omega::{HostPoolKv, KvAttention, KvGeometry}; 23 24 const CTX: usize = 128; 25 26 type Ctl = GenerationController; 27 28 fn ctl(graph: bool) -> Ctl { 29 let mut m = EchoChainModel::new(CTX); 30 m.graph_mode = graph; 31 GenerationController::new(m) 32 } 33 34 pub(crate) fn prompt(n: usize, seed: usize) -> Vec { 35 (0..n) 36 .map(|i| ((i * 7 + seed * 13 + 1) % 64) as u32) 37 .collect() 38 } 39 40 pub(crate) fn greedy(n: usize) -> GenerateParams { 41 GenerateParams::greedy(n, Vec::new()) 42 } 43 44 pub(crate) fn sampled(n: usize, seed: u64) -> GenerateParams { 45 GenerateParams { 46 max_new_tokens: n, 47 temperature: 1.0, 48 top_p: 1.0, 49 top_k: 0, 50 seed, 51 stop_token_ids: Vec::new(), 52 } 53 } 54 55 pub(crate) fn gen_with( 56 c: &mut GenerationController, 57 prompt: &[u32], 58 params: &GenerateParams, 59 sampler: &mut dyn Sampler, 60 constraint: Option<&mut dyn Constraint>, 61 ) -> Result<(Vec, GenerateOutcome), String> { 62 let mut out = Vec::new(); 63 let o = c.generate(prompt, params, sampler, constraint, &mut |t| { 64 out.push(t); 65 true 66 })?; 67 Ok((out, o)) 68 } 69 70 pub(crate) fn gen( 71 c: &mut GenerationController, 72 prompt: &[u32], 73 params: &GenerateParams, 74 constraint: Option<&mut dyn Constraint>, 75 ) -> Result<(Vec, GenerateOutcome), String> { 76 let mut s = SampleNext(params.clone()); 77 gen_with(c, prompt, params, &mut s, constraint) 78 } 79 80 /// A cold run on a fresh fake. 81 fn cold(prompt: &[u32], params: &GenerateParams) -> Vec { 82 gen(&mut ctl(false), prompt, params, None).unwrap().0 83 } 84 85 /// What the moved tests read beyond the seam: how many positions each layer of the cache holds 86 /// (as many layers as the model can show). 87 pub(crate) trait LayerFill { 88 fn layer_fill(&self) -> Vec; 89 } 90 91 impl LayerFill for EchoChainModel { 92 fn layer_fill(&self) -> Vec { 93 self.layer_lens() 94 } 95 } 96 97 /// Every layer holds exactly the ledger's positions. 98 pub(crate) fn assert_at_ledger(c: &GenerationController) { 99 let n = c.position(); 100 let fill = c.model().layer_fill(); 101 assert!(!fill.is_empty()); 102 assert_eq!( 103 fill, 104 vec![n; fill.len()], 105 "every layer must hold exactly position() = {n} rows" 106 ); 107 } 108 109 /// The outcome without its wall-clock fields. 110 pub(crate) fn counted(o: &GenerateOutcome) -> GenerateOutcome { 111 GenerateOutcome { 112 prefill_ms: 0, 113 decode_ms: 0, 114 ..o.clone() 115 } 116 } 117 118 fn decodes(calls: &[Call]) -> usize { 119 calls 120 .iter() 121 .filter(|c| matches!(c, Call::Decode { .. })) 122 .count() 123 } 124 125 /// Rules in order, then `then` forever. Records what it was shown. 126 struct Script { 127 rules: Vec>, 128 then: StepRule, 129 seen: Vec>, 130 } 131 132 impl Script { 133 fn new(rules: Vec>, then: StepRule) -> Self { 134 Self { 135 rules, 136 then, 137 seen: Vec::new(), 138 } 139 } 140 fn always(rule: StepRule) -> Self { 141 Self::new(Vec::new(), rule) 142 } 143 } 144 145 impl Constraint for Script { 146 fn rule(&mut self, _prompt: &[u32], generated: &[u32]) -> Result { 147 let i = self.seen.len(); 148 self.seen.push(generated.to_vec()); 149 self.rules 150 .get(i) 151 .cloned() 152 .unwrap_or_else(|| Ok(self.then.clone())) 153 } 154 } 155 156 /// A logits-wanting argmax that records the step counter it is given. 157 #[derive(Default)] 158 struct StepRecorder(Vec); 159 160 impl Sampler for StepRecorder { 161 fn wants_logits(&self) -> bool { 162 true 163 } 164 fn pick(&mut self, logits: &[f32], step: usize) -> u32 { 165 self.0.push(step); 166 sample_argmax(logits).0 167 } 168 } 169 170 // --------------------------------------------------------------------------------------------- 171 // The contract suite (I1 to I5) for any forward pass. 172 // --------------------------------------------------------------------------------------------- 173 174 fn read_logits(m: &mut M, head: usize) -> Vec { 175 match m.next(head, Want::Logits, &mut StepTiming::default()) { 176 Ok(Next::Logits(l)) => l.to_vec(), 177 other => panic!("Want::Logits must give logits, got {other:?}"), 178 } 179 } 180 181 /// From a model whose head 0 predicts the token at `pos`: decodes `n` greedy tokens starting 182 /// with `first`, returning every step's logits. 183 fn greedy_chain(m: &mut M, pos: usize, first: u32, n: usize) -> Vec> { 184 let mut t = StepTiming::default(); 185 let mut tok = first; 186 let mut out = Vec::new(); 187 for i in 0..n { 188 m.decode(pos + i, &[tok], &mut t).unwrap(); 189 let l = read_logits(m, 0); 190 tok = sample_argmax(&l).0; 191 out.push(l); 192 } 193 out 194 } 195 196 pub(crate) fn forward_pass_contract(make: &dyn Fn() -> M) { 197 let p = prompt(20, 1); // more than one KV block 198 let n = p.len(); 199 let mut t = StepTiming::default(); 200 201 // prefill of n tokens leaves exactly one head; a head is read once (I2). 202 let mut a = make(); 203 a.prefill(0, &p, &mut t).unwrap(); 204 assert!( 205 a.next(1, Want::Logits, &mut t).is_err(), 206 "prefill leaves head 0 only" 207 ); 208 let la = read_logits(&mut a, 0); 209 assert_eq!(la.len(), a.vocab()); 210 assert!( 211 a.next(0, Want::Logits, &mut t).is_err(), 212 "a head is read once (I2)" 213 ); 214 215 // Want::Greedy gives Token only as the argmax of that head's logits (I4): on the prefill 216 // head and on a decode head (the graph's held token). 217 let first = sample_argmax(&la).0; 218 let mut b = make(); 219 b.prefill(0, &p, &mut t).unwrap(); 220 match b.next(0, Want::Greedy, &mut t).unwrap() { 221 Next::Token(x) => assert_eq!(x, first), 222 Next::Logits(l) => assert_eq!(l, &la[..]), 223 } 224 a.decode(n, &[first], &mut t).unwrap(); 225 b.decode(n, &[first], &mut t).unwrap(); 226 let la2 = read_logits(&mut a, 0); 227 match b.next(0, Want::Greedy, &mut t).unwrap() { 228 Next::Token(x) => assert_eq!(x, sample_argmax(&la2).0), 229 Next::Logits(l) => assert_eq!(l, &la2[..]), 230 } 231 232 // A head read after a truncate that drops a row errors (I2). 233 let mut c = make(); 234 c.prefill(0, &p, &mut t).unwrap(); 235 c.kv().truncate(n - 1); 236 assert!( 237 c.next(0, Want::Logits, &mut t).is_err(), 238 "no head survives a truncate" 239 ); 240 241 // A head read after a new forward call gives the new call's head (I2): an unread decode 242 // head (on a graph, a held token) is replaced by the next prefill's head. 243 let mut g = make(); 244 g.prefill(0, &p, &mut t).unwrap(); 245 let _ = read_logits(&mut g, 0); 246 g.decode(n, &[first], &mut t).unwrap(); 247 let _ = read_logits(&mut g, 0); 248 g.prefill(n + 1, &[7, 9], &mut t).unwrap(); 249 let lg = read_logits(&mut g, 0); 250 let mut f = make(); 251 f.prefill(0, &p, &mut t).unwrap(); 252 let _ = read_logits(&mut f, 0); 253 f.decode(n, &[first], &mut t).unwrap(); 254 f.prefill(n + 1, &[7, 9], &mut t).unwrap(); 255 match f.next(0, Want::Greedy, &mut t).unwrap() { 256 Next::Token(x) => assert_eq!(x, sample_argmax(&lg).0), 257 Next::Logits(l) => assert_eq!(l, &lg[..]), 258 } 259 assert!(f.next(0, Want::Logits, &mut t).is_err()); 260 261 // A position the cache does not hold is refused (I1). 262 let mut d = make(); 263 assert!( 264 d.prefill(1, &p, &mut t).is_err(), 265 "prefill past an empty cache" 266 ); 267 let mut d = make(); 268 d.prefill(0, &p, &mut t).unwrap(); 269 assert!(d.decode(n + 1, &[first], &mut t).is_err(), "a gap"); 270 assert!(d.decode(n - 1, &[first], &mut t).is_err(), "an overwrite"); 271 272 // next_rows equals the gather of next(Logits). 273 let mut e = make(); 274 e.prefill(0, &p, &mut t).unwrap(); 275 let rows = [0u32, 5, 9, 31, 63]; 276 let mut out = [0f32; 5]; 277 e.next_rows(0, &rows, &mut out, &mut t).unwrap(); 278 let want: Vec = rows.iter().map(|&r| la[r as usize]).collect(); 279 assert_eq!(&out[..], &want[..]); 280 281 // Export, then import into a fresh model, then decode equals the uninterrupted run. 282 let mut u = make(); 283 u.prefill(0, &p, &mut t).unwrap(); 284 u.clear_pending(); 285 let reference = greedy_chain(&mut u, n, first, 8); 286 let mut s = make(); 287 s.prefill(0, &p, &mut t).unwrap(); 288 let bytes = s.kv().export_blocks(0, n).unwrap().unwrap(); 289 let mut r = make(); 290 r.kv().import_blocks(0, n, &bytes).unwrap().unwrap(); 291 assert_eq!(r.kv().len(), n); 292 assert_eq!(greedy_chain(&mut r, n, first, 8), reference); 293 294 // A multi-token decode leaves one head per token, each as a single decode would. 295 let mut m = make(); 296 if m.max_decode_batch() >= 3 { 297 m.prefill(0, &p, &mut t).unwrap(); 298 m.clear_pending(); 299 let toks = [first, 7, 11]; 300 m.decode(n, &toks, &mut t).unwrap(); 301 let mut one = make(); 302 one.prefill(0, &p, &mut t).unwrap(); 303 for (j, &tok) in toks.iter().enumerate() { 304 one.decode(n + j, &[tok], &mut t).unwrap(); 305 assert_eq!(read_logits(&mut m, j), read_logits(&mut one, 0), "head {j}"); 306 } 307 assert!(m.next(3, Want::Logits, &mut t).is_err()); 308 // A new forward call replaces every unread head (I2). 309 m.decode(n + 3, &[1, 2, 3], &mut t).unwrap(); 310 m.decode(n + 6, &[4], &mut t).unwrap(); 311 assert!( 312 m.next(1, Want::Logits, &mut t).is_err(), 313 "head 1 of the old call" 314 ); 315 assert!( 316 m.next(2, Want::Logits, &mut t).is_err(), 317 "head 2 of the old call" 318 ); 319 assert!(m.next(0, Want::Logits, &mut t).is_ok()); 320 } 321 } 322 323 #[test] 324 fn echo_chain_keeps_the_forward_pass_contract() { 325 forward_pass_contract(&|| EchoChainModel::new(CTX)); 326 forward_pass_contract(&|| { 327 let mut m = EchoChainModel::new(CTX); 328 m.graph_mode = true; 329 m 330 }); 331 forward_pass_contract(&|| { 332 let mut m = EchoChainModel::new(CTX); 333 m.graph_mode = true; 334 m.max_decode_batch = 3; 335 m 336 }); 337 } 338 339 // --------------------------------------------------------------------------------------------- 340 // The controller (moved tests, then the new ones of section 5). 341 // --------------------------------------------------------------------------------------------- 342 343 // The moved tests (ADR 0004 section 5), generic over the forward pass: each runs here on the 344 // fake and on the tiny MoE through the 30B adapter (`qwen3_moe_omega::forward_pass` tests). 345 346 /// A cold run on a fresh model. 347 pub(crate) fn cold_on( 348 make: &dyn Fn() -> M, 349 prompt: &[u32], 350 params: &GenerateParams, 351 ) -> Vec { 352 gen(&mut GenerationController::new(make()), prompt, params, None) 353 .unwrap() 354 .0 355 } 356 357 /// Returns the warm turn's outcome, so the caller can check its own prefill counters. 358 pub(crate) fn moved_prefix_reuse( 359 make: &dyn Fn() -> M, 360 ) -> GenerateOutcome { 361 let mut c = GenerationController::new(make()); 362 let p1 = prompt(10, 2); 363 let (first, o) = gen(&mut c, &p1, &greedy(4), None).unwrap(); 364 assert_eq!((o.reused_prompt_tokens, o.prompt_tokens), (0, 10)); 365 let mut p2 = c.history().to_vec(); 366 assert_eq!(p2.len(), 13, "prompt plus the three decoded tokens"); 367 assert_eq!(&p2[10..], &first[..3]); 368 p2.extend([5, 6, 7]); 369 let (warm, warm_outcome) = gen(&mut c, &p2, &greedy(8), None).unwrap(); 370 assert_eq!(warm_outcome.reused_prompt_tokens, 13); 371 assert_eq!(warm, cold_on(make, &p2, &greedy(8))); 372 assert_at_ledger(&c); 373 // A prompt equal to the whole history still prefills its last token; an unrelated prompt 374 // starts cold. 375 let h = c.history().to_vec(); 376 let (_, o) = gen(&mut c, &h, &greedy(2), None).unwrap(); 377 assert_eq!(o.reused_prompt_tokens, h.len() - 1); 378 let (_, o) = gen(&mut c, &[1, 2, 3], &greedy(2), None).unwrap(); 379 assert_eq!(o.reused_prompt_tokens, 0); 380 assert_at_ledger(&c); 381 warm_outcome 382 } 383 384 #[test] 385 fn prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run() { 386 let o = moved_prefix_reuse(&|| EchoChainModel::new(CTX)); 387 assert_eq!( 388 o.prefill_timing.launches, 3, 389 "only the new tokens are prefilled" 390 ); 391 } 392 393 #[test] 394 fn the_unreused_suffix_reaches_prefill_in_one_call() { 395 let mut c = ctl(false); 396 let p1 = prompt(10, 3); 397 let (_, _) = gen(&mut c, &p1, &greedy(4), None).unwrap(); 398 let mut p2 = c.history()[..12].to_vec(); 399 p2.extend([1, 2, 3, 4, 5]); 400 let before = c.model().calls().len(); 401 let (out, o) = gen(&mut c, &p2, &greedy(5), None).unwrap(); 402 assert_eq!(o.reused_prompt_tokens, 12); 403 let calls = c.model().calls()[before..].to_vec(); 404 let mut want = vec![Call::Prefill { pos: 12, len: 5 }]; 405 for (i, &t) in out[..out.len() - 1].iter().enumerate() { 406 want.push(Call::Decode { 407 pos: 17 + i, 408 tokens: vec![t], 409 }); 410 } 411 assert_eq!( 412 calls, want, 413 "one prefill, one decode per emitted token but the last" 414 ); 415 } 416 417 #[test] 418 fn greedy_with_chip_argmax_reads_no_logits() { 419 let p = prompt(12, 4); 420 let mut graph = ctl(true); 421 let (g, _) = gen(&mut graph, &p, &greedy(8), None).unwrap(); 422 let m = graph.model(); 423 // Every decode head here is a graph head (7 of them): asking it for Want::Logits would 424 // count 7 chip reads, so 0 shows the controller asked Want::Greedy and took the held token. 425 assert_eq!(m.chip_reads, 0, "greedy on the graph reads no logits back"); 426 assert_eq!(m.lm_heads, 1, "only the prefill head is a host output head"); 427 let mut host = ctl(false); 428 let (h, _) = gen(&mut host, &p, &greedy(8), None).unwrap(); 429 assert_eq!((host.model().lm_heads, host.model().chip_reads), (8, 0)); 430 assert_eq!(g, h, "graph and host greedy give the same tokens"); 431 432 let mut graph = ctl(true); 433 let (gs, o) = gen(&mut graph, &p, &sampled(8, 5), None).unwrap(); 434 assert_eq!(o.emitted_tokens, 8); 435 assert_eq!( 436 graph.model().chip_reads, 437 7, 438 "one read-back per decoded token" 439 ); 440 assert_eq!(graph.model().lm_heads, 1); 441 let mut host = ctl(false); 442 let (hs, _) = gen(&mut host, &p, &sampled(8, 5), None).unwrap(); 443 assert_eq!(gs, hs, "graph and host sampling give the same tokens"); 444 } 445 446 /// R1, red before green (ADR 0004 section 5): written against the loop without rollback, where 447 /// layer 0 keeps the half-written row; green once the controller cuts the cache to the ledger. 448 #[test] 449 fn a_forward_error_leaves_every_layer_at_the_ledger() { 450 // Mid-prefill on a warm turn. 451 let mut c = ctl(false); 452 let p1 = prompt(10, 5); 453 gen(&mut c, &p1, &greedy(4), None).unwrap(); 454 let h = c.history().to_vec(); 455 let mut p2 = h.clone(); 456 p2.extend([3, 4, 5, 6, 7, 8]); 457 c.model_mut().fail_at = Some(h.len() + 3); 458 let err = gen(&mut c, &p2, &greedy(8), None).unwrap_err(); 459 assert!(err.contains("injected failure"), "{err}"); 460 assert_eq!(c.history(), &h[..], "the ledger is unchanged"); 461 eprintln!( 462 "R1 mid-prefill: position {} layer lengths {:?}", 463 c.position(), 464 c.model().layer_lens() 465 ); 466 assert_at_ledger(&c); 467 c.model_mut().fail_at = None; 468 let (warm, _) = gen(&mut c, &p2, &greedy(8), None).unwrap(); 469 assert_eq!( 470 warm, 471 cold(&p2, &greedy(8)), 472 "the next turn equals a cold run" 473 ); 474 475 // Mid-decode. 476 let mut c = ctl(true); 477 let p = prompt(10, 6); 478 c.model_mut().fail_at = Some(p.len() + 2); 479 let mut out = Vec::new(); 480 let err = c 481 .generate(&p, &greedy(8), &mut SampleNext(greedy(8)), None, &mut |t| { 482 out.push(t); 483 true 484 }) 485 .unwrap_err(); 486 assert!(err.contains("injected failure"), "{err}"); 487 assert_eq!(c.position(), p.len() + 2); 488 assert_eq!(&c.history()[p.len()..], &out[..2]); 489 eprintln!( 490 "R1 mid-decode: position {} layer lengths {:?}", 491 c.position(), 492 c.model().layer_lens() 493 ); 494 assert_at_ledger(&c); 495 c.model_mut().fail_at = None; 496 let mut p3 = c.history().to_vec(); 497 p3.push(9); 498 let (warm, _) = gen(&mut c, &p3, &greedy(8), None).unwrap(); 499 assert_eq!(warm, cold(&p3, &greedy(8))); 500 } 501 502 pub(crate) fn moved_stops_caps_and_cancels(make: &dyn Fn() -> M) { 503 let p = prompt(10, 7); 504 let chain = cold_on(make, &p, &greedy(8)); 505 assert_eq!(chain.len(), 8); 506 let stop = chain[4]; 507 let i = chain.iter().position(|&t| t == stop).unwrap(); 508 let mut c = GenerationController::new(make()); 509 let (out, o) = gen(&mut c, &p, &GenerateParams::greedy(8, vec![stop]), None).unwrap(); 510 assert_eq!( 511 (&out[..], o.finish, o.emitted_tokens), 512 (&chain[..i], FinishReason::Stop, i) 513 ); 514 515 let mut c = GenerationController::new(make()); 516 let (out, o) = gen(&mut c, &p, &greedy(5), None).unwrap(); 517 assert_eq!((&out[..], o.finish), (&chain[..5], FinishReason::Length)); 518 519 let mut c = GenerationController::new(make()); 520 let mut out = Vec::new(); 521 let o = c 522 .generate(&p, &greedy(8), &mut SampleNext(greedy(8)), None, &mut |t| { 523 out.push(t); 524 out.len() < 3 525 }) 526 .unwrap(); 527 assert_eq!( 528 (&out[..], o.finish, o.emitted_tokens), 529 (&chain[..3], FinishReason::Cancelled, 3) 530 ); 531 } 532 533 #[test] 534 fn generate_stops_on_stop_ids_caps_length_and_cancels() { 535 moved_stops_caps_and_cancels(&|| EchoChainModel::new(CTX)); 536 } 537 538 #[test] 539 fn stop_and_cancel_tokens_are_never_stepped() { 540 let p = prompt(10, 8); 541 let chain = cold(&p, &greedy(8)); 542 let stop = chain[3]; 543 let i = chain.iter().position(|&t| t == stop).unwrap(); 544 let mut c = ctl(false); 545 gen(&mut c, &p, &GenerateParams::greedy(8, vec![stop]), None).unwrap(); 546 assert_eq!( 547 &c.history()[p.len()..], 548 &chain[..i], 549 "the stop token is not stored" 550 ); 551 assert_eq!(decodes(&c.model().calls()), i); 552 assert_at_ledger(&c); 553 554 let mut c = ctl(false); 555 let mut n = 0; 556 c.generate( 557 &p, 558 &greedy(8), 559 &mut SampleNext(greedy(8)), 560 None, 561 &mut |_| { 562 n += 1; 563 n < 3 564 }, 565 ) 566 .unwrap(); 567 assert_eq!( 568 &c.history()[p.len()..], 569 &chain[..2], 570 "the cancelled token is not stored" 571 ); 572 assert_eq!(decodes(&c.model().calls()), 2); 573 assert_at_ledger(&c); 574 } 575 576 #[test] 577 fn each_on_token_fires_before_the_next_decode() { 578 let p = prompt(9, 9); 579 let mut c = ctl(false); 580 let log = c.model().log_handle(); 581 let mut out = Vec::new(); 582 c.generate(&p, &greedy(5), &mut SampleNext(greedy(5)), None, &mut |t| { 583 log.lock().unwrap().push(Call::Emitted(t)); 584 out.push(t); 585 true 586 }) 587 .unwrap(); 588 let mut want = vec![Call::Prefill { pos: 0, len: 9 }]; 589 for (i, &t) in out.iter().enumerate() { 590 want.push(Call::Emitted(t)); 591 if i + 1 < out.len() { 592 want.push(Call::Decode { 593 pos: 9 + i, 594 tokens: vec![t], 595 }); 596 } 597 } 598 assert_eq!(c.model().calls(), want); 599 } 600 601 #[test] 602 fn a_full_context_ends_with_length_and_no_error() { 603 let mut c = GenerationController::new(EchoChainModel::new(32)); 604 assert_eq!(c.max_context_tokens(), 32); 605 let p = prompt(30, 10); 606 let (out, o) = gen(&mut c, &p, &greedy(10), None).unwrap(); 607 assert_eq!((out.len(), o.finish), (3, FinishReason::Length)); 608 assert_eq!(c.position(), 32); 609 assert_at_ledger(&c); 610 assert!( 611 gen(&mut c, &prompt(32, 10), &greedy(1), None).is_err(), 612 "a prompt that fills the context" 613 ); 614 } 615 616 /// `make_a` runs the uninterrupted engine, `make_b` the one the prefix is restored into. 617 pub(crate) fn moved_restored_prefix( 618 make_a: &dyn Fn() -> M, 619 make_b: &dyn Fn() -> M, 620 ) { 621 let mut a = GenerationController::new(make_a()); 622 gen(&mut a, &prompt(20, 11), &greedy(8), None).unwrap(); 623 let h = a.history().to_vec(); 624 let bytes = a.export_kv(0, h.len()).unwrap(); 625 let mut next = h.clone(); 626 next.extend([4, 2]); 627 let (want, _) = gen(&mut a, &next, &greedy(8), None).unwrap(); 628 629 let mut b = GenerationController::new(make_b()); 630 b.restore_kv(&h, &bytes).unwrap(); 631 assert_eq!(b.history(), &h[..]); 632 assert_at_ledger(&b); 633 assert_eq!( 634 b.export_kv(0, h.len()).unwrap(), 635 bytes, 636 "import then export is byte-identical" 637 ); 638 let (got, o) = gen(&mut b, &next, &greedy(8), None).unwrap(); 639 assert_eq!(o.reused_prompt_tokens, h.len()); 640 assert_eq!(got, want); 641 assert_eq!(got, cold_on(make_b, &next, &greedy(8))); 642 } 643 644 #[test] 645 fn restored_prefix_continues_exactly_like_the_uninterrupted_engine() { 646 moved_restored_prefix(&|| EchoChainModel::new(CTX), &|| { 647 let mut m = EchoChainModel::new(CTX); 648 m.graph_mode = true; 649 m 650 }); 651 } 652 653 pub(crate) fn moved_failed_restore(make: &dyn Fn() -> M) { 654 let p = prompt(20, 12); 655 let mut a = GenerationController::new(make()); 656 gen(&mut a, &p, &greedy(4), None).unwrap(); 657 let h = a.history().to_vec(); 658 let mut snap = a.export_kv(0, h.len()).unwrap(); 659 assert!(a.export_kv(0, h.len() + 1).is_err(), "past the ledger"); 660 661 let mut b = GenerationController::new(make()); 662 gen(&mut b, &[1, 2, 3, 4], &greedy(2), None).unwrap(); 663 assert!(b.restore_kv(&h, &snap[..snap.len() - 2]).is_err()); 664 assert_eq!(b.position(), 0); 665 assert_at_ledger(&b); 666 let last = snap.len() - 1; 667 snap[last] ^= 1; // a padding byte set 668 assert!(b.restore_kv(&h, &snap).is_err()); 669 assert!(b.restore_kv(&[], &[]).is_err()); 670 let ctx = b.max_context_tokens(); 671 assert!(b.restore_kv(&vec![1u32; ctx], &snap).is_err()); 672 assert_eq!(b.position(), 0); 673 assert_at_ledger(&b); 674 let (got, o) = gen(&mut b, &p, &greedy(8), None).unwrap(); 675 assert_eq!(o.reused_prompt_tokens, 0); 676 assert_eq!( 677 got, 678 cold_on(make, &p, &greedy(8)), 679 "plain prefill after a refused restore" 680 ); 681 } 682 683 #[test] 684 fn a_failed_restore_resets_the_ledger() { 685 moved_failed_restore(&|| EchoChainModel::new(CTX)); 686 } 687 688 #[test] 689 fn max_new_tokens_zero_reads_no_head() { 690 let mut c = ctl(false); 691 let mut rule = Script::always(StepRule::Any); 692 let (out, o) = gen(&mut c, &prompt(8, 13), &greedy(0), Some(&mut rule)).unwrap(); 693 assert_eq!((out.len(), o.finish), (0, FinishReason::Length)); 694 let m = c.model(); 695 assert_eq!((m.lm_heads, m.chip_reads, m.rows_reads), (0, 0, 0)); 696 assert_eq!(m.calls(), vec![Call::Prefill { pos: 0, len: 8 }]); 697 assert!(rule.seen.is_empty(), "no step, no rule"); 698 } 699 700 #[test] 701 fn timing_buckets_sum_the_calls_of_each_phase() { 702 let p = prompt(10, 14); 703 let (_, o) = gen(&mut ctl(false), &p, &greedy(4), None).unwrap(); 704 assert_eq!(o.prefill_timing.launches, 10); 705 assert_eq!( 706 o.decode_timing.launches, 707 3 + 4, 708 "three decodes and four host output heads" 709 ); 710 let (_, o) = gen(&mut ctl(true), &p, &greedy(4), None).unwrap(); 711 assert_eq!( 712 o.decode_timing.launches, 713 3 + 1, 714 "the prefill head is the only host head" 715 ); 716 assert_eq!( 717 (o.decode_timing.graph_tokens, o.decode_timing.graph_submits), 718 (3, 3) 719 ); 720 } 721 722 #[test] 723 fn kv_identity_names_the_salt_and_a_mutant_refuses() { 724 let a = ctl(false).kv_identity().unwrap(); 725 assert_eq!(a.kind, "echo-chain"); 726 let mut m = EchoChainModel::new(CTX); 727 m.salt = 1; 728 let b = GenerationController::new(m).kv_identity().unwrap(); 729 assert_ne!( 730 a, b, 731 "the salt changes K/V bytes, so it changes the identity" 732 ); 733 let mut g = EchoChainModel::new(CTX); 734 g.graph_mode = true; 735 assert_eq!(GenerationController::new(g).kv_identity().unwrap(), a); 736 let bad = EchoChainModel::with_kv(Box::new(CorruptRowKv::new(CTX, 1, 0).unwrap())); 737 assert!(GenerationController::new(bad).kv_identity().is_err()); 738 } 739 740 #[test] 741 fn locked_hands_out_the_controller_and_is_send_and_sync() { 742 fn send_sync() {} 743 send_sync::>(); 744 let p = prompt(10, 15); 745 let l = Locked::new(ctl(false)); 746 let (out, _) = l 747 .with_controller(|c| gen(c, &p, &greedy(8), None)) 748 .unwrap() 749 .unwrap(); 750 assert_eq!(out, cold(&p, &greedy(8))); 751 assert_eq!(l.with_controller(|c| c.position()).unwrap(), 17); 752 } 753 754 // --------------------------------------------------------------------------------------------- 755 // Constraints (section 2.3), end to end on the fake. 756 // --------------------------------------------------------------------------------------------- 757 758 #[test] 759 fn an_allowed_set_picks_the_best_token_inside_it() { 760 let p = prompt(12, 16); 761 let u0 = cold(&p, &greedy(1))[0]; 762 // logits[i] = ((h + 37 i) % 64) / 64 with the maximum at u0, so the score of i is 763 // (63 + 37 (i - u0)) mod 64. 764 let score = |i: u32| (63 + 37 * ((i + 64 - u0) % 64)) % 64; 765 let allowed: Vec = { 766 let mut v: Vec = (1..=8).map(|k| (u0 + k) % 64).collect(); 767 v.sort_unstable(); 768 v 769 }; 770 let best = *allowed.iter().max_by_key(|&&i| score(i)).unwrap(); 771 assert_ne!(best, u0); 772 let mut c = ctl(true); 773 let mut rule = Script::always(StepRule::Allow(allowed.clone())); 774 let (out, _) = gen(&mut c, &p, &greedy(1), Some(&mut rule)).unwrap(); 775 assert_eq!(out, vec![best]); 776 let m = c.model(); 777 assert_eq!((m.rows_reads, m.chip_reads), (1, 0)); 778 779 // Over many steps, greedy and sampled, every token is inside the set. 780 for params in [greedy(10), sampled(10, 3)] { 781 let mut c = ctl(true); 782 let mut rule = Script::always(StepRule::Allow(allowed.clone())); 783 let (out, _) = gen(&mut c, &p, ¶ms, Some(&mut rule)).unwrap(); 784 assert_eq!(out.len(), 10); 785 assert!(out.iter().all(|t| allowed.contains(t)), "{out:?}"); 786 assert_eq!(c.model().rows_reads, 10); 787 } 788 } 789 790 #[test] 791 fn a_forced_token_is_emitted_decoded_and_counted() { 792 let p = prompt(12, 17); 793 let u0 = cold(&p, &greedy(1))[0]; 794 let forced = (u0 + 1) % 64; 795 let mut c = ctl(true); 796 let mut rule = Script::new(vec![Ok(StepRule::Force(forced))], StepRule::Any); 797 let mut steps = StepRecorder::default(); 798 let (out, _) = gen_with(&mut c, &p, &greedy(9), &mut steps, Some(&mut rule)).unwrap(); 799 assert_eq!(out[0], forced, "in the stream"); 800 assert_eq!(c.history()[p.len()], forced, "in the history"); 801 assert_eq!( 802 c.model().calls()[1], 803 Call::Decode { 804 pos: p.len(), 805 tokens: vec![forced] 806 } 807 ); 808 assert_eq!( 809 steps.0, 810 (1..9).collect::>(), 811 "the forced step advanced the counter" 812 ); 813 assert_eq!( 814 rule.seen[1], 815 vec![forced], 816 "the constraint sees the forced token" 817 ); 818 // The forced token's K/V bytes equal a prompt that ended with it, and so does the rest. 819 let mut q = p.clone(); 820 q.push(forced); 821 let mut d = ctl(false); 822 let (rest, _) = gen(&mut d, &q, &greedy(8), None).unwrap(); 823 assert_eq!(&out[1..], &rest[..]); 824 assert_eq!( 825 c.export_kv(0, q.len()).unwrap(), 826 d.export_kv(0, q.len()).unwrap() 827 ); 828 // No head is read for a forced step. 829 let mut c = ctl(true); 830 let mut rule = Script::always(StepRule::Force(forced)); 831 gen(&mut c, &p, &greedy(1), Some(&mut rule)).unwrap(); 832 let m = c.model(); 833 assert_eq!((m.lm_heads, m.chip_reads, m.rows_reads), (0, 0, 0)); 834 } 835 836 #[test] 837 fn finish_ends_with_finish_reason_constraint() { 838 let p = prompt(12, 18); 839 let chain = cold(&p, &greedy(8)); 840 let mut c = ctl(false); 841 let mut rule = Script::new(vec![Ok(StepRule::Any); 3], StepRule::Finish); 842 let (out, o) = gen(&mut c, &p, &greedy(8), Some(&mut rule)).unwrap(); 843 assert_eq!( 844 (&out[..], o.finish, o.emitted_tokens), 845 (&chain[..3], FinishReason::Constraint, 3) 846 ); 847 assert_eq!(&c.history()[p.len()..], &chain[..3]); 848 assert_at_ledger(&c); 849 assert_eq!(c.model().lm_heads, 3, "the finishing step reads no head"); 850 } 851 852 #[test] 853 fn any_is_byte_identical_to_no_constraint() { 854 let p = prompt(12, 19); 855 for graph in [false, true] { 856 for params in [greedy(10), sampled(10, 21)] { 857 let mut a = ctl(graph); 858 let (ta, oa) = gen(&mut a, &p, ¶ms, None).unwrap(); 859 let mut b = ctl(graph); 860 let mut rule = Script::always(StepRule::Any); 861 let (tb, ob) = gen(&mut b, &p, ¶ms, Some(&mut rule)).unwrap(); 862 assert_eq!(ta, tb, "same tokens"); 863 assert_eq!(counted(&oa), counted(&ob), "same outcome and counters"); 864 assert_eq!(a.model().calls(), b.model().calls(), "same call log"); 865 let (ma, mb) = (a.model(), b.model()); 866 assert_eq!( 867 (ma.chip_reads, ma.lm_heads, ma.rows_reads), 868 (mb.chip_reads, mb.lm_heads, mb.rows_reads) 869 ); 870 assert_eq!( 871 (ma.rows_reads, mb.rows_reads), 872 (0, 0), 873 "next_rows is never called" 874 ); 875 assert_eq!(rule.seen.len(), 10, "asked once per step"); 876 } 877 } 878 } 879 880 #[test] 881 fn a_constraint_error_rolls_back_like_a_forward_error() { 882 let p = prompt(12, 20); 883 let chain = cold(&p, &greedy(8)); 884 let bad_rules = [ 885 Err("the automaton broke".to_string()), 886 Ok(StepRule::Allow(Vec::new())), 887 Ok(StepRule::Allow(vec![5, 3])), 888 Ok(StepRule::Allow(vec![3, ECHO_VOCAB as u32])), 889 Ok(StepRule::Force(ECHO_VOCAB as u32)), 890 ]; 891 for bad in bad_rules { 892 let mut c = ctl(true); 893 let mut rule = Script::new( 894 vec![Ok(StepRule::Any), Ok(StepRule::Any), bad.clone()], 895 StepRule::Any, 896 ); 897 assert!( 898 gen(&mut c, &p, &greedy(8), Some(&mut rule)).is_err(), 899 "{bad:?}" 900 ); 901 assert_eq!(&c.history()[p.len()..], &chain[..2], "{bad:?}"); 902 assert_at_ledger(&c); 903 assert!( 904 c.model_mut() 905 .next(0, Want::Logits, &mut StepTiming::default()) 906 .is_err(), 907 "the rollback forgets the pending head ({bad:?})" 908 ); 909 let mut q = c.history().to_vec(); 910 q.push(1); 911 let (warm, _) = gen(&mut c, &q, &greedy(8), None).unwrap(); 912 assert_eq!(warm, cold(&q, &greedy(8)), "{bad:?}"); 913 } 914 } 915 916 #[test] 917 fn seeded_sampling_replays_under_a_constraint() { 918 let p = prompt(12, 21); 919 let allowed: Vec = (0..64).step_by(4).collect(); 920 let run = |seed: u64| { 921 let mut rule = Script::always(StepRule::Allow(allowed.clone())); 922 gen(&mut ctl(false), &p, &sampled(16, seed), Some(&mut rule)) 923 .unwrap() 924 .0 925 }; 926 let a = run(7); 927 assert_eq!(a, run(7), "same seed, same tokens"); 928 assert!(a.iter().all(|t| allowed.contains(t))); 929 assert_ne!(a, run(8), "another seed, other tokens"); 930 } 931 932 // --------------------------------------------------------------------------------------------- 933 // The two negative controls of section 4: the fake must see a damaged or foreign K/V row. 934 // --------------------------------------------------------------------------------------------- 935 936 #[test] 937 fn negative_control_a_corrupted_surviving_row_changes_the_warm_run() { 938 let p1 = prompt(20, 22); 939 let corrupt = CorruptRowKv::new(CTX, 5, 1).unwrap(); 940 let mut c = GenerationController::new(EchoChainModel::with_kv(Box::new(corrupt))); 941 gen(&mut c, &p1, &greedy(4), None).unwrap(); 942 let mut p2 = c.history().to_vec(); 943 p2.extend([9, 10]); 944 let (damaged, o) = gen(&mut c, &p2, &greedy(8), None).unwrap(); 945 assert_eq!( 946 o.reused_prompt_tokens, 23, 947 "the warm run reuses the corrupted row" 948 ); 949 950 // Baseline: the same warm run on a clean cache equals the cold run. 951 let mut clean = ctl(false); 952 gen(&mut clean, &p1, &greedy(4), None).unwrap(); 953 let (clean_warm, _) = gen(&mut clean, &p2, &greedy(8), None).unwrap(); 954 let cold_run = cold(&p2, &greedy(8)); 955 assert_eq!(clean_warm, cold_run); 956 957 let differ = damaged 958 .iter() 959 .zip(&cold_run) 960 .filter(|(a, b)| a != b) 961 .count(); 962 eprintln!("negative control 1 (corrupt row at position 5, layer 1):\n cold {cold_run:?}\n damaged {damaged:?}\n {differ} of 8 tokens differ"); 963 assert_ne!( 964 damaged, cold_run, 965 "a corrupted surviving row must change the warm run" 966 ); 967 } 968 969 #[test] 970 fn negative_control_restoring_a_under_b_continues_differently() { 971 let mut a = ctl(false); 972 gen(&mut a, &prompt(20, 23), &greedy(4), None).unwrap(); 973 let ha = a.history().to_vec(); 974 let bytes = a.export_kv(0, ha.len()).unwrap(); 975 let hb: Vec = ha.iter().map(|t| (t + 1) % 64).collect(); 976 977 // Baseline: A's payload under A's tokens continues like a cold run on A. 978 let mut next_a = ha.clone(); 979 next_a.push(3); 980 let mut r = ctl(false); 981 r.restore_kv(&ha, &bytes).unwrap(); 982 assert_eq!( 983 gen(&mut r, &next_a, &greedy(8), None).unwrap().0, 984 cold(&next_a, &greedy(8)) 985 ); 986 987 let mut next_b = hb.clone(); 988 next_b.push(3); 989 let mut r = ctl(false); 990 r.restore_kv(&hb, &bytes).unwrap(); 991 let (foreign, o) = gen(&mut r, &next_b, &greedy(8), None).unwrap(); 992 assert_eq!( 993 o.reused_prompt_tokens, 994 hb.len(), 995 "the foreign payload is reused" 996 ); 997 let cold_b = cold(&next_b, &greedy(8)); 998 let differ = foreign.iter().zip(&cold_b).filter(|(a, b)| a != b).count(); 999 eprintln!("negative control 2 (A's payload restored under B's tokens):\n cold B {cold_b:?}\n A as B {foreign:?}\n {differ} of 8 tokens differ"); 1000 assert_ne!( 1001 foreign, cold_b, 1002 "a foreign payload must continue differently" 1003 ); 1004 } 1005 1006 // --------------------------------------------------------------------------------------------- 1007 // Review additions: the controller's own clear_pending calls, a sampler that leaves the allowed 1008 // set, and a cache that cannot export or import. 1009 // --------------------------------------------------------------------------------------------- 1010 1011 /// Whether head 0 is still pending (reading it consumes it). 1012 fn head_pending(c: &mut Ctl) -> bool { 1013 c.model_mut() 1014 .next(0, Want::Logits, &mut StepTiming::default()) 1015 .is_ok() 1016 } 1017 1018 /// A generation that a constraint finishes leaves its last head unread. 1019 fn finished_with_a_pending_head(graph: bool) -> Ctl { 1020 let mut c = ctl(graph); 1021 let mut rule = Script::new(vec![Ok(StepRule::Any); 2], StepRule::Finish); 1022 gen(&mut c, &prompt(12, 24), &greedy(8), Some(&mut rule)).unwrap(); 1023 c 1024 } 1025 1026 #[test] 1027 fn rewind_a_new_generation_and_a_forced_token_forget_the_pending_head() { 1028 for graph in [false, true] { 1029 assert!( 1030 head_pending(&mut finished_with_a_pending_head(graph)), 1031 "precondition" 1032 ); 1033 1034 // rewind, even one that keeps every row. 1035 let mut c = finished_with_a_pending_head(graph); 1036 let n = c.position(); 1037 c.rewind(n); 1038 assert!(!head_pending(&mut c), "rewind clears pending heads"); 1039 1040 // The start of every generation, even one refused before it touches the cache. 1041 let mut c = finished_with_a_pending_head(graph); 1042 assert!(gen(&mut c, &[], &greedy(4), None).is_err()); 1043 assert!(!head_pending(&mut c), "generate clears pending heads first"); 1044 1045 // A forced token discards the head it did not read. 1046 let mut c = ctl(graph); 1047 let mut rule = Script::always(StepRule::Force(3)); 1048 let (out, _) = gen(&mut c, &prompt(12, 25), &greedy(1), Some(&mut rule)).unwrap(); 1049 assert_eq!(out, vec![3]); 1050 assert!( 1051 !head_pending(&mut c), 1052 "a forced step clears the unread head" 1053 ); 1054 } 1055 } 1056 1057 /// A sampler that always picks one token, whatever the logits say. 1058 struct Picks(u32); 1059 1060 impl Sampler for Picks { 1061 fn wants_logits(&self) -> bool { 1062 true 1063 } 1064 fn pick(&mut self, _logits: &[f32], _step: usize) -> u32 { 1065 self.0 1066 } 1067 } 1068 1069 #[test] 1070 fn a_pick_outside_the_allowed_set_is_an_error() { 1071 let p = prompt(12, 26); 1072 let mut c = ctl(false); 1073 let mut rule = Script::new( 1074 vec![Ok(StepRule::Any), Ok(StepRule::Allow(vec![1, 2, 3]))], 1075 StepRule::Any, 1076 ); 1077 let mut out = Vec::new(); 1078 let r = c.generate(&p, &greedy(8), &mut Picks(0), Some(&mut rule), &mut |t| { 1079 out.push(t); 1080 true 1081 }); 1082 assert!( 1083 r.is_err(), 1084 "token 0 is outside the allowed set: {r:?} {out:?}" 1085 ); 1086 assert_eq!(out, vec![0], "only the unconstrained step emitted"); 1087 assert_eq!(c.position(), p.len() + 1); 1088 assert_at_ledger(&c); 1089 assert!(!head_pending(&mut c)); 1090 } 1091 1092 /// The fake's pool with persistence switched off (export and import answer `None`). 1093 struct NoPersistKv(HostPoolKv); 1094 1095 impl KvStore for NoPersistKv { 1096 fn geometry(&self) -> KvGeometry { 1097 self.0.geometry() 1098 } 1099 fn capacity(&self) -> usize { 1100 self.0.capacity() 1101 } 1102 fn len(&self) -> usize { 1103 self.0.len() 1104 } 1105 fn truncate(&mut self, len: usize) { 1106 self.0.truncate(len) 1107 } 1108 } 1109 1110 impl KvAttention for NoPersistKv { 1111 fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String> { 1112 self.0.append(layer, pos, k, v) 1113 } 1114 fn attend( 1115 &mut self, 1116 layer: usize, 1117 q: &[f32], 1118 context_len: usize, 1119 out: &mut [f32], 1120 ) -> Result { 1121 self.0.attend(layer, q, context_len, out) 1122 } 1123 fn resident(&self) -> bool { 1124 false 1125 } 1126 } 1127 1128 impl EchoKv for NoPersistKv { 1129 fn layer_len(&self, layer: usize) -> usize { 1130 self.0.layer_len(layer) 1131 } 1132 } 1133 1134 #[test] 1135 fn a_cache_that_cannot_persist_refuses_export_and_restore() { 1136 let pool = HostPoolKv::new(&echo_geometry(), CTX).unwrap(); 1137 let mut c = GenerationController::new(EchoChainModel::with_kv(Box::new(NoPersistKv(pool)))); 1138 let p = prompt(20, 27); 1139 gen(&mut c, &p, &greedy(4), None).unwrap(); 1140 let err = c.export_kv(0, 16).unwrap_err(); 1141 assert!(err.contains("cannot export"), "{err}"); 1142 let err = c.restore_kv(&p, &[0u8; 8]).unwrap_err(); 1143 assert!(err.contains("cannot import"), "{err}"); 1144 assert_eq!((c.position(), c.model().layer_lens()), (0, vec![0, 0])); 1145 let (got, _) = gen(&mut c, &p, &greedy(8), None).unwrap(); 1146 assert_eq!(got, cold(&p, &greedy(8))); 1147 }