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/tests/resident_weights.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 / tests / resident_weights.rs` 515 lines ยท 18794 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 //! GB10 weight ownership (sovereign-core #277 cut C): resident bf16 upload straight from the 17 //! checkpoint, no host f32 copy of any matmul weight. 18 //! 19 //! No chip is used. The "device" is a fake that keeps the uploaded `[k][n]` bf16 bits and 20 //! computes with the same host arithmetic as the reference backend, so a Host load and a 21 //! Resident load of the same checkpoint must give bit-identical logits if (and only if) the 22 //! streaming, the transpose and the dispatch are right. 23 24 use aien_abi_core::RopeParams; 25 use aien_inference_abi::{ 26 bf16_bits_as_uploaded_today, load_model_config, load_resident_weights, resident_load_wanted, 27 transpose_bf16_for_upload, CheckpointError, MatrixRef, MatrixWeight, NativeTransformerBackend, 28 ReferenceCpuBackend, ResidentHandle, ResidentUploader, ResidentWeight, TensorBackend, 29 TransformerWeights, 30 }; 31 use std::path::PathBuf; 32 use std::sync::{Arc, Mutex}; 33 34 fn tiny_dir() -> PathBuf { 35 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/qwen3-tiny") 36 } 37 38 // ---- numerics: bf16 -> f32 -> bf16 over every pattern ---- 39 40 /// Independent software model of `(__bf16)f` on aarch64 (round to nearest even, NaN quieted), 41 /// not sharing code with the loader. It was checked against gcc's own `(__bf16)` cast for all 42 /// 65536 patterns on this host: 126 differences, all signaling NaNs (see the PR text). 43 fn narrow_like_omega(f: f32) -> u16 { 44 let bits = f.to_bits(); 45 if f.is_nan() { 46 return ((bits >> 16) as u16) | 0x0040; 47 } 48 let lsb = (bits >> 16) & 1; 49 (bits.wrapping_add(0x7fff + lsb) >> 16) as u16 50 } 51 52 #[test] 53 fn bf16_widen_then_narrow_is_exact_except_signaling_nans_which_omega_quiets() { 54 let mut changed = Vec::new(); 55 let (mut denormals, mut nans, mut infs) = (0u32, 0u32, 0u32); 56 for p in 0..=u16::MAX { 57 let widened = f32::from_bits((p as u32) << 16); 58 let via_omega = narrow_like_omega(widened); 59 // What the loader sends must equal what omega's f32 path stores today, for every pattern. 60 assert_eq!( 61 bf16_bits_as_uploaded_today(p), 62 via_omega, 63 "pattern {p:#06x}" 64 ); 65 if via_omega != p { 66 changed.push(p); 67 } 68 let exp = (p >> 7) & 0xff; 69 let man = p & 0x7f; 70 if exp == 0 && man != 0 { 71 denormals += 1; 72 } 73 if exp == 0xff && man != 0 { 74 nans += 1; 75 } 76 if exp == 0xff && man == 0 { 77 infs += 1; 78 } 79 } 80 // Every NaN payload, every denormal, both infinities and both zeros are in the sweep. 81 assert_eq!((denormals, nans, infs), (254, 254, 2)); 82 // The only patterns that change: signaling NaNs (quiet bit clear), 63 per sign. 83 assert_eq!(changed.len(), 126); 84 for p in &changed { 85 assert_eq!(p & 0x7f80, 0x7f80); 86 assert_eq!(p & 0x0040, 0, "{p:#06x} is not a signaling NaN"); 87 assert_ne!(p & 0x007f, 0); 88 assert_eq!(bf16_bits_as_uploaded_today(*p), p | 0x0040); 89 } 90 // Everything else, including all denormals and the quiet NaN payloads, is bit-identical. 91 assert!(!changed.contains(&0x0001) && !changed.contains(&0x7fc1) && !changed.contains(&0x8000)); 92 } 93 94 #[test] 95 fn transpose_puts_w_out_in_into_k_by_n() { 96 let (n, k) = (3usize, 5usize); 97 let src: Vec = (0..(n * k) as u16).map(|i| 0x3f80 + i).collect(); // finite bf16 values 98 let raw: Vec = src.iter().flat_map(|b| b.to_le_bytes()).collect(); 99 let mut dst = vec![9u16; 4]; 100 transpose_bf16_for_upload(&raw, n, k, &mut dst); 101 assert_eq!(dst.len(), n * k); 102 for o in 0..n { 103 for i in 0..k { 104 assert_eq!(dst[i * n + o], src[o * k + i], "o={o} i={i}"); 105 } 106 } 107 // Larger than one 64x64 tile in both directions, odd sizes. 108 let (n, k) = (131usize, 70usize); 109 let src: Vec = (0..(n * k)).map(|i| (i as u16) | 0x4000).collect(); 110 let raw: Vec = src.iter().flat_map(|b| b.to_le_bytes()).collect(); 111 transpose_bf16_for_upload(&raw, n, k, &mut dst); 112 for o in 0..n { 113 for i in 0..k { 114 assert_eq!(dst[i * n + o], src[o * k + i]); 115 } 116 } 117 } 118 119 // ---- a fake device ---- 120 121 #[derive(Debug)] 122 struct FakeDevice { 123 k: usize, 124 n: usize, 125 /// W as `[n][k]` f32, rebuilt from the uploaded `[k][n]` bf16 bits. 126 w: Vec, 127 calls: Mutex, 128 } 129 130 impl ResidentHandle for FakeDevice { 131 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { 132 assert_eq!(a.len(), m * self.k); 133 assert_eq!(c.len(), m * self.n); 134 for r in 0..m { 135 aien_inference_abi::tensor::matmul_vec( 136 &a[r * self.k..(r + 1) * self.k], 137 &self.w, 138 &mut c[r * self.n..(r + 1) * self.n], 139 self.k, 140 self.n, 141 ); 142 } 143 *self.calls.lock().unwrap() += 1; 144 Ok(1) 145 } 146 } 147 148 #[derive(Default)] 149 struct FakeUploader { 150 shapes: Mutex>, 151 /// Zero the Nth uploaded matrix (0-based; negative control). Layer 0 uploads q, k, v, o, 152 /// gate, up, down, then the fused q|k|v (7) and gate|up (8) the forward paths read. 153 corrupt_at: Option, 154 /// Fail on the Nth upload (0-based). 155 fail_at: Option, 156 } 157 158 impl ResidentUploader for FakeUploader { 159 fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result { 160 let idx = { 161 let mut s = self.shapes.lock().unwrap(); 162 s.push((k, n)); 163 s.len() - 1 164 }; 165 if self.fail_at == Some(idx) { 166 return Err("NV_ERR_NO_MEMORY (fake)".to_string()); 167 } 168 assert_eq!(bits.len(), k * n); 169 let mut w = vec![0.0f32; n * k]; 170 for i in 0..k { 171 for o in 0..n { 172 w[o * k + i] = f32::from_bits((bits[i * n + o] as u32) << 16); 173 } 174 } 175 if self.corrupt_at == Some(idx) { 176 w.iter_mut().for_each(|v| *v = 0.0); 177 } 178 Ok(ResidentWeight::new( 179 k, 180 n, 181 Arc::new(FakeDevice { 182 k, 183 n, 184 w, 185 calls: Mutex::new(0), 186 }), 187 )) 188 } 189 } 190 191 /// The reference backend plus the one thing the real GB10 backend adds: it can run a resident 192 /// weight. Everything else delegates, so a difference can only come from the weights. 193 struct DeviceLikeBackend(ReferenceCpuBackend); 194 195 impl TensorBackend for DeviceLikeBackend { 196 fn name(&self) -> &'static str { 197 "DeviceLikeBackend (test)" 198 } 199 fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { 200 self.0.rmsnorm(out, x, weight, eps) 201 } 202 fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { 203 self.0.rmsnorm_heads(x, weight, head_dim, eps) 204 } 205 fn apply_rope( 206 &self, 207 q: &mut [f32], 208 k: &mut [f32], 209 pos: usize, 210 head_dim: usize, 211 nq: usize, 212 nkv: usize, 213 rope: &RopeParams, 214 ) { 215 self.0.apply_rope(q, k, pos, head_dim, nq, nkv, rope) 216 } 217 fn matmul_vec(&self, out: &mut [f32], x: &[f32], w: &[f32], out_dim: usize, in_dim: usize) { 218 self.0.matmul_vec(out, x, w, out_dim, in_dim) 219 } 220 fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { 221 self.0.swiglu(out, gate, up) 222 } 223 fn gqa_attention( 224 &self, 225 out: &mut [f32], 226 q: &[f32], 227 kc: &[f32], 228 vc: &[f32], 229 seq_len: usize, 230 nq: usize, 231 nkv: usize, 232 head_dim: usize, 233 ) { 234 self.0 235 .gqa_attention(out, q, kc, vc, seq_len, nq, nkv, head_dim) 236 } 237 fn compute_logits(&self, l: &mut [f32], h: &[f32], e: &[f32], v: usize, hd: usize) { 238 self.0.compute_logits(l, h, e, v, hd) 239 } 240 fn matmul_batch_w( 241 &self, 242 out: &mut [f32], 243 x: &[f32], 244 w: MatrixRef<'_>, 245 batch: usize, 246 in_dim: usize, 247 out_dim: usize, 248 ) { 249 match w { 250 MatrixRef::Host(h) => self.0.matmul_batch(out, x, h, batch, in_dim, out_dim), 251 MatrixRef::Resident(r) => { 252 assert_eq!((r.k(), r.n()), (in_dim, out_dim)); 253 r.matmul_f32(batch, x, out).unwrap(); 254 } 255 } 256 } 257 fn matmul_vec_w( 258 &self, 259 out: &mut [f32], 260 x: &[f32], 261 w: MatrixRef<'_>, 262 out_dim: usize, 263 in_dim: usize, 264 ) { 265 self.matmul_batch_w(out, x, w, 1, in_dim, out_dim) 266 } 267 fn compute_logits_w( 268 &self, 269 l: &mut [f32], 270 h: &[f32], 271 w: MatrixRef<'_>, 272 vocab: usize, 273 hidden: usize, 274 ) { 275 self.matmul_batch_w(l, h, w, 1, hidden, vocab) 276 } 277 } 278 279 fn host_weights() -> TransformerWeights { 280 let dir = tiny_dir(); 281 let config = load_model_config(&dir).unwrap(); 282 TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config).unwrap() 283 } 284 285 fn resident_weights(up: &FakeUploader) -> Result { 286 let dir = tiny_dir(); 287 let config = load_model_config(&dir).unwrap(); 288 load_resident_weights(dir.join("model.safetensors"), &config, up, &mut |_| {}) 289 } 290 291 fn max_abs(a: &[f32], b: &[f32]) -> f32 { 292 assert_eq!(a.len(), b.len()); 293 a.iter() 294 .zip(b) 295 .map(|(x, y)| (x - y).abs()) 296 .fold(0.0, f32::max) 297 } 298 299 const IDS: [u32; 6] = [3, 17, 5, 9, 1, 22]; 300 301 fn prefill_logits(weights: TransformerWeights) -> Vec { 302 let mut be = NativeTransformerBackend::with_backend( 303 weights, 304 Arc::new(DeviceLikeBackend(Default::default())), 305 ); 306 be.prefill_sequence(1, &IDS).expect("prefill") 307 } 308 309 #[test] 310 fn resident_load_holds_no_host_matmul_weight_and_matches_host_logits_exactly() { 311 let up = FakeUploader::default(); 312 let w = resident_weights(&up).expect("resident load"); 313 let layers = w.layers.len(); 314 // Every one of the seven matmul weights per layer, plus the (tied) head, is resident. 315 for l in &w.layers { 316 for m in [ 317 &l.q_proj, 318 &l.k_proj, 319 &l.v_proj, 320 &l.o_proj, 321 &l.gate_proj, 322 &l.up_proj, 323 &l.down_proj, 324 ] { 325 assert!(m.is_resident()); 326 } 327 // The fused q|k|v and gate|up matrices (sc#384) are resident too, 2 more uploads per layer. 328 assert!(l.qkv_proj.as_ref().is_some_and(MatrixWeight::is_resident)); 329 assert!(l 330 .gate_up_proj 331 .as_ref() 332 .is_some_and(MatrixWeight::is_resident)); 333 } 334 assert!(w.config.tie_word_embeddings); 335 assert!(matches!(w.lm_head, Some(MatrixWeight::Resident(_)))); 336 assert_eq!(up.shapes.lock().unwrap().len(), layers * 9 + 1); 337 // The host keeps what the host reads: embedding rows and norms (readers: see the PR text). 338 assert_eq!(w.embed_tokens, host_weights().embed_tokens); 339 assert_eq!(w.final_norm, host_weights().final_norm); 340 341 let got = prefill_logits(w); 342 let want = prefill_logits(host_weights()); 343 assert_eq!( 344 got, want, 345 "resident logits must be bit-identical to host logits" 346 ); 347 } 348 349 #[test] 350 fn negative_control_a_wrong_resident_matrix_moves_the_logits() { 351 let up = FakeUploader { 352 // The fused q|k|v of layer 0: the matrix the prefill really reads (a zeroed single 353 // q_proj would move nothing, which is the point of the fused path). 354 corrupt_at: Some(7), 355 ..Default::default() 356 }; 357 let got = prefill_logits(resident_weights(&up).unwrap()); 358 let want = prefill_logits(host_weights()); 359 assert!(max_abs(&got, &want) > 1e-3, "comparison would be vacuous"); 360 } 361 362 #[test] 363 fn uploads_run_layer_by_layer_then_the_head() { 364 let dir = tiny_dir(); 365 let config = load_model_config(&dir).unwrap(); 366 let mut names = Vec::new(); 367 load_resident_weights( 368 dir.join("model.safetensors"), 369 &config, 370 &FakeUploader::default(), 371 &mut |n| names.push(n.to_string()), 372 ) 373 .unwrap(); 374 assert_eq!( 375 names.first().unwrap(), 376 "model.layers.0.self_attn.q_proj.weight" 377 ); 378 assert_eq!(names.last().unwrap(), "model.embed_tokens.weight"); 379 // 7 single matrices + the fused q|k|v and gate|up per layer, then the head. 380 assert_eq!(names.len(), config.num_layers * 9 + 1); 381 assert!(names.iter().any(|n| n.ends_with("q_proj.weight+model.layers.0.self_attn.k_proj.weight+model.layers.0.self_attn.v_proj.weight"))); 382 } 383 384 #[test] 385 fn an_upload_failure_is_a_named_error_never_a_host_copy() { 386 let up = FakeUploader { 387 fail_at: Some(3), 388 ..Default::default() 389 }; 390 match resident_weights(&up) { 391 Err(CheckpointError::ResidentUpload { tensor, message }) => { 392 assert_eq!(tensor, "model.layers.0.self_attn.o_proj.weight"); 393 assert!(message.contains("NV_ERR_NO_MEMORY")); 394 } 395 other => panic!("expected ResidentUpload, got {:?}", other.map(|_| ())), 396 } 397 } 398 399 #[test] 400 fn a_missing_tensor_is_refused_before_any_upload() { 401 let dir = tiny_dir(); 402 let mut config = load_model_config(&dir).unwrap(); 403 config.num_layers += 1; // the file has no layer N 404 let up = FakeUploader::default(); 405 let r = load_resident_weights(dir.join("model.safetensors"), &config, &up, &mut |_| {}); 406 assert!(matches!(r, Err(CheckpointError::MissingTensor(_)))); 407 assert!( 408 up.shapes.lock().unwrap().is_empty(), 409 "uploaded before validating" 410 ); 411 } 412 413 #[test] 414 #[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] 415 fn the_cpu_reference_backend_refuses_a_resident_weight_by_name() { 416 let w = resident_weights(&FakeUploader::default()).unwrap(); 417 let be = ReferenceCpuBackend::new(); 418 let mut out = vec![0.0; w.config.num_heads * w.config.head_dim]; 419 let x = vec![0.0; w.config.hidden_dim()]; 420 let (od, id) = (out.len(), x.len()); 421 be.matmul_vec_w(&mut out, &x, w.layers[0].q_proj.as_ref(), od, id); 422 } 423 424 #[test] 425 #[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] 426 fn host_slice_access_to_a_resident_weight_is_refused_by_name() { 427 let w = resident_weights(&FakeUploader::default()).unwrap(); 428 let _ = w.layers[0].q_proj.len(); 429 } 430 431 #[test] 432 fn resident_load_is_chosen_only_on_the_native_strict_enabled_qwen3_path() { 433 let dir = tiny_dir(); 434 let tiny = load_model_config(&dir).unwrap(); // qk_norm, head_dim 16 435 let mut q4b = tiny.clone(); 436 q4b.head_dim = 128; // the head_dim the GB10 engine accepts for Qwen3 437 // (native, strict, enabled, accepted Qwen3) -> resident 438 assert!(resident_load_wanted(true, true, true, &q4b)); 439 // each condition off -> host f32 load, unchanged 440 assert!(!resident_load_wanted(false, true, true, &q4b)); // stub build / no GB10 441 assert!(!resident_load_wanted(true, false, true, &q4b)); // dev-fallback needs host values 442 assert!(!resident_load_wanted(true, true, false, &q4b)); // Qwen3 switched off (=0): refused 443 assert!(!resident_load_wanted(true, true, true, &tiny)); // engine refuses head_dim 16 444 let mut llama = q4b.clone(); 445 llama.qk_norm = false; // other models keep their path 446 assert!(!resident_load_wanted(true, true, true, &llama)); 447 } 448 449 #[test] 450 fn streamed_checkpoint_reads_the_same_bytes_as_the_whole_file_loader() { 451 let dir = tiny_dir(); 452 let config = load_model_config(&dir).unwrap(); 453 let catalog = aien_inference_abi::llama_catalog(&config); 454 let path = dir.join("model.safetensors"); 455 let whole = aien_inference_abi::load_checkpoint_with_catalog(&path, &catalog).unwrap(); 456 let streamed = aien_inference_abi::StreamedCheckpoint::open(&path, &catalog).unwrap(); 457 let mut buf = Vec::new(); 458 for (name, shape) in &catalog { 459 let n = streamed.read_bf16_bytes(name, &mut buf).unwrap(); 460 assert_eq!(n, shape.iter().product::(), "{name}"); 461 assert_eq!(buf.as_slice(), whole.tensor_bytes(name).unwrap(), "{name}"); 462 assert_eq!(streamed.shape(name).unwrap(), shape.as_slice()); 463 } 464 // A catalog tensor the file lacks is refused when the checkpoint is opened. 465 let mut bad = catalog.clone(); 466 bad.push(("model.layers.9.mlp.up_proj.weight".to_string(), vec![4, 4])); 467 assert!(matches!( 468 aien_inference_abi::StreamedCheckpoint::open(&path, &bad), 469 Err(CheckpointError::MissingTensor(_)) 470 )); 471 } 472 473 fn fake_resident(k: usize, n: usize) -> (ResidentWeight, Vec) { 474 // W [n][k] with bf16-exact values, and its resident twin built through the real transpose. 475 let w: Vec = (0..n * k) 476 .map(|i| f32::from_bits((0x3f00 + (i % 200) as u32) << 16)) 477 .collect(); 478 let raw: Vec = w 479 .iter() 480 .flat_map(|v| ((v.to_bits() >> 16) as u16).to_le_bytes()) 481 .collect(); 482 let mut bits = Vec::new(); 483 transpose_bf16_for_upload(&raw, n, k, &mut bits); 484 (FakeUploader::default().upload_bf16(k, n, &bits).unwrap(), w) 485 } 486 487 #[test] 488 fn omega_backend_runs_a_resident_weight_through_the_resident_handle() { 489 let (k, n) = (16usize, 24usize); 490 let (r, w) = fake_resident(k, n); 491 let be = aien_inference_abi::OmegaGb10Backend::new(); // stub build: no chip, no host path used 492 let x: Vec = (0..3 * k).map(|i| (i % 7) as f32 * 0.25).collect(); 493 let mut got = vec![0.0; 3 * n]; 494 be.matmul_batch_w(&mut got, &x, MatrixRef::Resident(&r), 3, k, n); 495 let mut want = vec![0.0; 3 * n]; 496 ReferenceCpuBackend::new().matmul_batch(&mut want, &x, &w, 3, k, n); 497 assert_eq!(got, want); 498 assert_eq!(be.chip_calls(), 1); 499 assert_eq!(be.fallback_count(), 0); 500 let mut one = vec![0.0; n]; 501 be.matmul_vec_w(&mut one, &x[..k], MatrixRef::Resident(&r), n, k); 502 assert_eq!(one, want[..n]); 503 be.compute_logits_w(&mut one, &x[..k], MatrixRef::Resident(&r), n, k); 504 assert_eq!(one, want[..n]); 505 assert_eq!(be.chip_calls(), 3); 506 } 507 508 #[test] 509 #[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] 510 fn omega_backend_refuses_a_resident_weight_of_the_wrong_shape() { 511 let (r, _) = fake_resident(16, 24); 512 let be = aien_inference_abi::OmegaGb10Backend::new(); 513 let mut out = vec![0.0; 32]; 514 be.matmul_vec_w(&mut out, &[0.0; 16], MatrixRef::Resident(&r), 32, 16); 515 }