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-inference-abi / tests / transformer_parity.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 | //! Numerical correctness and parity test suite for NativeTransformerBackend. |
| 17 | //! Verifies transformer execution, RMSNorm, RoPE, GQA, and multi-step autoregressive generation. |
| 18 | |
| 19 | use aien_inference_abi::{ |
| 20 | AienInferenceBackend, DecodeOutput, ModelConfig, NativeTransformerBackend, SamplingParams, |
| 21 | ScheduledBatch, SequenceRequest, TransformerWeights, |
| 22 | }; |
| 23 | use std::collections::HashMap; |
| 24 | |
| 25 | fn test_model_config() -> ModelConfig { |
| 26 | ModelConfig { |
| 27 | model_id: "aien-transformer-micro-v1".to_string(), |
| 28 | max_sequence_length: 512, |
| 29 | block_size: 16, |
| 30 | num_layers: 2, |
| 31 | num_heads: 4, |
| 32 | head_dim: 16, |
| 33 | num_kv_heads: 2, // GQA: 4 query heads, 2 KV heads |
| 34 | hidden_dim: 64, |
| 35 | intermediate_dim: 128, |
| 36 | vocab_size: 256, |
| 37 | rms_norm_eps: 1e-5, |
| 38 | rope_theta: 10000.0, |
| 39 | rope_scaling: None, |
| 40 | tie_word_embeddings: false, |
| 41 | eos_token_ids: Vec::new(), |
| 42 | qk_norm: false, |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | #[tokio::test] |
| 47 | async fn test_native_transformer_prefill_and_decode_step() { |
| 48 | let config = test_model_config(); |
| 49 | let mut backend = NativeTransformerBackend::with_reference_weights(&config); |
| 50 | |
| 51 | // 1. Prefill Step |
| 52 | let prompt = vec![12u32, 45u32, 89u32, 120u32]; |
| 53 | let req = SequenceRequest { |
| 54 | request_id: 1001, |
| 55 | prompt_tokens: prompt.clone(), |
| 56 | sampling_params: SamplingParams { |
| 57 | temperature: 0.0, // Greedy argmax |
| 58 | top_p: 1.0, |
| 59 | max_tokens: 32, |
| 60 | stop_token_ids: vec![0, 1, 2], |
| 61 | }, |
| 62 | arrival_time_ns: 0, |
| 63 | priority: 1, |
| 64 | }; |
| 65 | |
| 66 | let prefill_batch = ScheduledBatch { |
| 67 | prefill_requests: vec![req], |
| 68 | decode_requests: Vec::new(), |
| 69 | block_tables: { |
| 70 | let mut m = HashMap::new(); |
| 71 | m.insert(1001, vec![0, 1]); |
| 72 | m |
| 73 | }, |
| 74 | step_id: 1, |
| 75 | }; |
| 76 | |
| 77 | let (outputs, metrics) = backend.execute_step(&prefill_batch).await.unwrap(); |
| 78 | |
| 79 | assert_eq!(outputs.len(), 1); |
| 80 | assert_eq!(metrics.prefill_tokens_processed, 4); |
| 81 | assert_eq!(metrics.decode_tokens_emitted, 1); |
| 82 | |
| 83 | let _first_token = match &outputs[0] { |
| 84 | DecodeOutput::Token { |
| 85 | request_id, |
| 86 | token_id, |
| 87 | logprob, |
| 88 | } => { |
| 89 | assert_eq!(*request_id, 1001); |
| 90 | assert!(*token_id < 256, "Token ID must be within vocab_size"); |
| 91 | assert!(logprob.is_some()); |
| 92 | let lp = logprob.unwrap(); |
| 93 | assert!(lp <= 0.0, "Logprob must be non-positive"); |
| 94 | *token_id |
| 95 | } |
| 96 | _ => panic!("Expected DecodeOutput::Token"), |
| 97 | }; |
| 98 | |
| 99 | // 2. Decode Step |
| 100 | let decode_batch = ScheduledBatch { |
| 101 | prefill_requests: Vec::new(), |
| 102 | decode_requests: vec![1001], |
| 103 | block_tables: { |
| 104 | let mut m = HashMap::new(); |
| 105 | m.insert(1001, vec![0, 1]); |
| 106 | m |
| 107 | }, |
| 108 | step_id: 2, |
| 109 | }; |
| 110 | |
| 111 | let (decode_outputs, decode_metrics) = backend.execute_step(&decode_batch).await.unwrap(); |
| 112 | |
| 113 | assert_eq!(decode_outputs.len(), 1); |
| 114 | assert_eq!(decode_metrics.prefill_tokens_processed, 0); |
| 115 | assert_eq!(decode_metrics.decode_tokens_emitted, 1); |
| 116 | |
| 117 | match &decode_outputs[0] { |
| 118 | DecodeOutput::Token { |
| 119 | request_id, |
| 120 | token_id, |
| 121 | logprob, |
| 122 | } => { |
| 123 | assert_eq!(*request_id, 1001); |
| 124 | assert!(*token_id < 256); |
| 125 | assert!(logprob.is_some()); |
| 126 | let lp = logprob.unwrap(); |
| 127 | assert!(lp <= 0.0); |
| 128 | } |
| 129 | DecodeOutput::Finished { request_id, .. } => { |
| 130 | assert_eq!(*request_id, 1001); |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | #[tokio::test] |
| 136 | async fn test_multi_step_autoregressive_generation() { |
| 137 | let config = test_model_config(); |
| 138 | let mut backend = NativeTransformerBackend::with_reference_weights(&config); |
| 139 | |
| 140 | // Initial prompt |
| 141 | let req = SequenceRequest { |
| 142 | request_id: 2002, |
| 143 | prompt_tokens: vec![5, 10, 15], |
| 144 | sampling_params: SamplingParams { |
| 145 | temperature: 0.0, // deterministic greedy |
| 146 | top_p: 1.0, |
| 147 | max_tokens: 16, |
| 148 | stop_token_ids: vec![0], |
| 149 | }, |
| 150 | arrival_time_ns: 0, |
| 151 | priority: 1, |
| 152 | }; |
| 153 | |
| 154 | let mut batch = ScheduledBatch { |
| 155 | prefill_requests: vec![req], |
| 156 | decode_requests: Vec::new(), |
| 157 | block_tables: { |
| 158 | let mut m = HashMap::new(); |
| 159 | m.insert(2002, vec![0, 1]); |
| 160 | m |
| 161 | }, |
| 162 | step_id: 1, |
| 163 | }; |
| 164 | |
| 165 | let mut generated_tokens = Vec::new(); |
| 166 | |
| 167 | // Step 1: Prefill |
| 168 | let (outputs, _) = backend.execute_step(&batch).await.unwrap(); |
| 169 | if let DecodeOutput::Token { token_id, .. } = &outputs[0] { |
| 170 | generated_tokens.push(*token_id); |
| 171 | } |
| 172 | |
| 173 | // Steps 2..6: 5 autoregressive decode steps |
| 174 | for step in 2..=6 { |
| 175 | batch.prefill_requests.clear(); |
| 176 | batch.decode_requests = vec![2002]; |
| 177 | batch.step_id = step; |
| 178 | |
| 179 | let (step_outputs, metrics) = backend.execute_step(&batch).await.unwrap(); |
| 180 | assert_eq!(step_outputs.len(), 1); |
| 181 | assert_eq!(metrics.decode_tokens_emitted, 1); |
| 182 | |
| 183 | match &step_outputs[0] { |
| 184 | DecodeOutput::Token { token_id, .. } => { |
| 185 | generated_tokens.push(*token_id); |
| 186 | } |
| 187 | DecodeOutput::Finished { .. } => break, |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | assert!( |
| 192 | !generated_tokens.is_empty(), |
| 193 | "Must have generated real model tokens" |
| 194 | ); |
| 195 | // Verify sequence history |
| 196 | let seq_state = backend.sequences.get(&2002).unwrap(); |
| 197 | assert_eq!(seq_state.tokens.len(), 3 + generated_tokens.len()); |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn test_safetensors_bytes_parser() { |
| 202 | let config = test_model_config(); |
| 203 | |
| 204 | // Construct a valid minimal safetensors binary buffer |
| 205 | let header_json = |
| 206 | r#"{"model.norm.weight":{"dtype":"F32","shape":[64],"data_offsets":[0,256]}}"#; |
| 207 | let header_bytes = header_json.as_bytes(); |
| 208 | let header_len = header_bytes.len() as u64; |
| 209 | |
| 210 | let mut buffer = Vec::new(); |
| 211 | buffer.extend_from_slice(&header_len.to_le_bytes()); |
| 212 | buffer.extend_from_slice(header_bytes); |
| 213 | |
| 214 | // 64 floats = 256 bytes |
| 215 | let raw_floats: Vec<f32> = (0..64).map(|i| (i as f32) * 0.1).collect(); |
| 216 | for f in raw_floats { |
| 217 | buffer.extend_from_slice(&f.to_le_bytes()); |
| 218 | } |
| 219 | |
| 220 | let weights = TransformerWeights::from_safetensors_bytes(&buffer, &config).unwrap(); |
| 221 | assert_eq!(weights.final_norm.len(), 64); |
| 222 | assert!((weights.final_norm[1] - 0.1).abs() < 1e-6); |
| 223 | assert!((weights.final_norm[10] - 1.0).abs() < 1e-6); |
| 224 | } |
| 225 | |
| 226 | #[tokio::test] |
| 227 | async fn test_blackwell_vs_reference_cpu_autoregressive_parity() { |
| 228 | let config = test_model_config(); |
| 229 | let mut cpu_backend = NativeTransformerBackend::with_reference_weights(&config); |
| 230 | let mut gpu_backend = NativeTransformerBackend::with_blackwell_backend(&config); |
| 231 | |
| 232 | let prompt = vec![7u32, 19u32, 42u32, 108u32]; |
| 233 | let req_cpu = SequenceRequest { |
| 234 | request_id: 3001, |
| 235 | prompt_tokens: prompt.clone(), |
| 236 | sampling_params: SamplingParams { |
| 237 | temperature: 0.0, |
| 238 | top_p: 1.0, |
| 239 | max_tokens: 16, |
| 240 | stop_token_ids: vec![0], |
| 241 | }, |
| 242 | arrival_time_ns: 0, |
| 243 | priority: 1, |
| 244 | }; |
| 245 | let req_gpu = SequenceRequest { |
| 246 | request_id: 3001, |
| 247 | prompt_tokens: prompt.clone(), |
| 248 | sampling_params: SamplingParams { |
| 249 | temperature: 0.0, |
| 250 | top_p: 1.0, |
| 251 | max_tokens: 16, |
| 252 | stop_token_ids: vec![0], |
| 253 | }, |
| 254 | arrival_time_ns: 0, |
| 255 | priority: 1, |
| 256 | }; |
| 257 | |
| 258 | let mut batch_cpu = ScheduledBatch { |
| 259 | prefill_requests: vec![req_cpu], |
| 260 | decode_requests: Vec::new(), |
| 261 | block_tables: { |
| 262 | let mut m = HashMap::new(); |
| 263 | m.insert(3001, vec![0, 1]); |
| 264 | m |
| 265 | }, |
| 266 | step_id: 1, |
| 267 | }; |
| 268 | let mut batch_gpu = ScheduledBatch { |
| 269 | prefill_requests: vec![req_gpu], |
| 270 | decode_requests: Vec::new(), |
| 271 | block_tables: { |
| 272 | let mut m = HashMap::new(); |
| 273 | m.insert(3001, vec![0, 1]); |
| 274 | m |
| 275 | }, |
| 276 | step_id: 1, |
| 277 | }; |
| 278 | |
| 279 | // The micro config uses head_dim 16, which omega attention does not support (see |
| 280 | // omega_backend.rs), and a stub build has no engine at all, so the "GPU" leg is never |
| 281 | // fully native here. A strict process must refuse it. A dev process runs it with |
| 282 | // counted fallbacks; in a stub build both legs are then the same reference math, so |
| 283 | // this is a wiring check, not chip parity. Chip parity lives in |
| 284 | // tests/omega_backend_parity.rs and the strict real-model gate (heavy queue). |
| 285 | let native = aien_omega_gpu::is_native(); |
| 286 | if aien_inference_abi::strict::production_strict() { |
| 287 | let probe = batch_gpu.clone(); |
| 288 | let refused = tokio::spawn(async move { gpu_backend.execute_step(&probe).await }) |
| 289 | .await |
| 290 | .expect_err("a strict process must refuse a GPU leg that cannot run natively"); |
| 291 | assert!(refused.is_panic(), "{refused}"); |
| 292 | let payload = refused.into_panic(); |
| 293 | let msg = payload |
| 294 | .downcast_ref::<String>() |
| 295 | .cloned() |
| 296 | .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string())) |
| 297 | .unwrap_or_default(); |
| 298 | assert!( |
| 299 | msg.contains(aien_inference_abi::strict::STRICT_VIOLATION_PREFIX), |
| 300 | "{msg}" |
| 301 | ); |
| 302 | return; |
| 303 | } |
| 304 | let mut cpu_tokens = Vec::new(); |
| 305 | let mut gpu_tokens = Vec::new(); |
| 306 | |
| 307 | let (out_cpu, _) = cpu_backend.execute_step(&batch_cpu).await.unwrap(); |
| 308 | let (out_gpu, _) = gpu_backend.execute_step(&batch_gpu).await.unwrap(); |
| 309 | |
| 310 | if let ( |
| 311 | DecodeOutput::Token { |
| 312 | token_id: t_cpu, .. |
| 313 | }, |
| 314 | DecodeOutput::Token { |
| 315 | token_id: t_gpu, .. |
| 316 | }, |
| 317 | ) = (&out_cpu[0], &out_gpu[0]) |
| 318 | { |
| 319 | if !native { |
| 320 | assert_eq!( |
| 321 | t_cpu, t_gpu, |
| 322 | "Prefill first token mismatch between CPU and the GPU leg" |
| 323 | ); |
| 324 | } |
| 325 | cpu_tokens.push(*t_cpu); |
| 326 | gpu_tokens.push(*t_gpu); |
| 327 | } |
| 328 | |
| 329 | for step in 2..=8 { |
| 330 | batch_cpu.prefill_requests.clear(); |
| 331 | batch_cpu.decode_requests = vec![3001]; |
| 332 | batch_cpu.step_id = step; |
| 333 | |
| 334 | batch_gpu.prefill_requests.clear(); |
| 335 | batch_gpu.decode_requests = vec![3001]; |
| 336 | batch_gpu.step_id = step; |
| 337 | |
| 338 | let (step_out_cpu, _) = cpu_backend.execute_step(&batch_cpu).await.unwrap(); |
| 339 | let (step_out_gpu, _) = gpu_backend.execute_step(&batch_gpu).await.unwrap(); |
| 340 | |
| 341 | if let ( |
| 342 | DecodeOutput::Token { |
| 343 | token_id: t_cpu, .. |
| 344 | }, |
| 345 | DecodeOutput::Token { |
| 346 | token_id: t_gpu, .. |
| 347 | }, |
| 348 | ) = (&step_out_cpu[0], &step_out_gpu[0]) |
| 349 | { |
| 350 | if !native { |
| 351 | assert_eq!( |
| 352 | t_cpu, t_gpu, |
| 353 | "Decode step {} token mismatch: CPU={}, GPU={}", |
| 354 | step, t_cpu, t_gpu |
| 355 | ); |
| 356 | } |
| 357 | cpu_tokens.push(*t_cpu); |
| 358 | gpu_tokens.push(*t_gpu); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // Dev run: the GPU leg cannot be fully native (see above), so its fallbacks must show. |
| 363 | let fallbacks = gpu_backend.tensor_backend.fallback_count(); |
| 364 | assert!( |
| 365 | fallbacks > 0, |
| 366 | "the GPU leg ran {fallbacks} counted fallbacks; expected some" |
| 367 | ); |
| 368 | if !native { |
| 369 | assert_eq!( |
| 370 | cpu_tokens, gpu_tokens, |
| 371 | "stub dev build: both legs are the reference math and must match bitwise" |
| 372 | ); |
| 373 | } |
| 374 | println!( |
| 375 | "Parity verified over {} tokens: {:?}", |
| 376 | cpu_tokens.len(), |
| 377 | cpu_tokens |
| 378 | ); |
| 379 | } |
| 380 | |
| 381 | #[tokio::test] |
| 382 | async fn test_multi_sequence_batched_decode_parity_with_sequential() { |
| 383 | let config = test_model_config(); |
| 384 | let weights = TransformerWeights::reference_test_weights(&config); |
| 385 | |
| 386 | let mut backend_seq = NativeTransformerBackend::new(weights.clone()); |
| 387 | let mut backend_batch = NativeTransformerBackend::new(weights); |
| 388 | |
| 389 | let num_seqs = 8; |
| 390 | let seq_ids: Vec<u64> = (1001..1001 + num_seqs as u64).collect(); |
| 391 | |
| 392 | // 1. Prefill all 8 sequences on both backends |
| 393 | for (i, &seq_id) in seq_ids.iter().enumerate() { |
| 394 | let prompt = vec![ |
| 395 | (10 + i * 3) as u32, |
| 396 | (25 + i * 7) as u32, |
| 397 | (40 + i * 11) as u32, |
| 398 | ]; |
| 399 | let req = SequenceRequest { |
| 400 | request_id: seq_id, |
| 401 | prompt_tokens: prompt, |
| 402 | sampling_params: SamplingParams { |
| 403 | temperature: 0.0, |
| 404 | top_p: 1.0, |
| 405 | max_tokens: 16, |
| 406 | stop_token_ids: vec![0], |
| 407 | }, |
| 408 | arrival_time_ns: 0, |
| 409 | priority: 1, |
| 410 | }; |
| 411 | |
| 412 | let mut block_tables = HashMap::new(); |
| 413 | block_tables.insert(seq_id, vec![i * 2, i * 2 + 1]); |
| 414 | |
| 415 | let batch = ScheduledBatch { |
| 416 | prefill_requests: vec![req], |
| 417 | decode_requests: Vec::new(), |
| 418 | block_tables, |
| 419 | step_id: 1, |
| 420 | }; |
| 421 | |
| 422 | let (out_seq, _) = backend_seq.execute_step(&batch).await.unwrap(); |
| 423 | let (out_batch, _) = backend_batch.execute_step(&batch).await.unwrap(); |
| 424 | |
| 425 | match (&out_seq[0], &out_batch[0]) { |
| 426 | ( |
| 427 | DecodeOutput::Token { |
| 428 | token_id: t1, |
| 429 | logprob: lp1, |
| 430 | .. |
| 431 | }, |
| 432 | DecodeOutput::Token { |
| 433 | token_id: t2, |
| 434 | logprob: lp2, |
| 435 | .. |
| 436 | }, |
| 437 | ) => { |
| 438 | assert_eq!(t1, t2, "Prefill token mismatch for seq_id {}", seq_id); |
| 439 | assert!( |
| 440 | (lp1.unwrap() - lp2.unwrap()).abs() < 1e-4, |
| 441 | "Logprob mismatch for seq_id {}", |
| 442 | seq_id |
| 443 | ); |
| 444 | } |
| 445 | _ => panic!("Expected DecodeOutput::Token"), |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // 2. Perform 5 decode steps: sequential (1 sequence per batch) vs batched (all 8 sequences per batch) |
| 450 | for step in 2..=6 { |
| 451 | // Sequential execution: 8 individual batches of size 1 |
| 452 | let mut seq_step_tokens = HashMap::new(); |
| 453 | for &seq_id in &seq_ids { |
| 454 | let mut block_tables = HashMap::new(); |
| 455 | block_tables.insert(seq_id, vec![0, 1]); |
| 456 | |
| 457 | let batch = ScheduledBatch { |
| 458 | prefill_requests: Vec::new(), |
| 459 | decode_requests: vec![seq_id], |
| 460 | block_tables, |
| 461 | step_id: step, |
| 462 | }; |
| 463 | |
| 464 | let (outputs, _) = backend_seq.execute_step(&batch).await.unwrap(); |
| 465 | assert_eq!(outputs.len(), 1); |
| 466 | if let DecodeOutput::Token { token_id, .. } = outputs[0] { |
| 467 | seq_step_tokens.insert(seq_id, token_id); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | // Batched execution: 1 single batch with D = 8 sequences |
| 472 | let mut batched_block_tables = HashMap::new(); |
| 473 | for (i, &seq_id) in seq_ids.iter().enumerate() { |
| 474 | batched_block_tables.insert(seq_id, vec![i * 2, i * 2 + 1]); |
| 475 | } |
| 476 | |
| 477 | let batch = ScheduledBatch { |
| 478 | prefill_requests: Vec::new(), |
| 479 | decode_requests: seq_ids.clone(), |
| 480 | block_tables: batched_block_tables, |
| 481 | step_id: step, |
| 482 | }; |
| 483 | |
| 484 | let (batched_outputs, metrics) = backend_batch.execute_step(&batch).await.unwrap(); |
| 485 | assert_eq!(batched_outputs.len(), num_seqs); |
| 486 | assert_eq!(metrics.decode_tokens_emitted, num_seqs); |
| 487 | |
| 488 | // Verify exact token parity across all 8 sequences |
| 489 | for out in &batched_outputs { |
| 490 | if let DecodeOutput::Token { |
| 491 | request_id, |
| 492 | token_id, |
| 493 | .. |
| 494 | } = out |
| 495 | { |
| 496 | let expected_tok = seq_step_tokens.get(request_id).copied().unwrap(); |
| 497 | assert_eq!( |
| 498 | *token_id, expected_tok, |
| 499 | "Step {} mismatch for sequence {}: batched={}, sequential={}", |
| 500 | step, request_id, token_id, expected_tok |
| 501 | ); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | // 3. Verify entire token trajectory is identical across all 8 sequences |
| 507 | for &seq_id in &seq_ids { |
| 508 | let tokens_seq = &backend_seq.sequences.get(&seq_id).unwrap().tokens; |
| 509 | let tokens_batch = &backend_batch.sequences.get(&seq_id).unwrap().tokens; |
| 510 | assert_eq!( |
| 511 | tokens_seq, tokens_batch, |
| 512 | "Full token history mismatch for seq_id {}", |
| 513 | seq_id |
| 514 | ); |
| 515 | } |
| 516 | } |