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-runtime / tests / compute_config_binding_test.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 | //! C6a (sc#484, ADR 0003 section 1.2.1, review finding 1): what the stored |
| 17 | //! bytes were computed with must be part of their identity. |
| 18 | //! |
| 19 | //! - `modelconfig_field_mutation_changes_compute_digest`: every `ModelConfig` |
| 20 | //! field is mutated one at a time. The test destructures `ModelConfig` |
| 21 | //! without `..`, so a new field is a compile error here until its author |
| 22 | //! decides "bound" or "excluded with a reason" (the production conversion in |
| 23 | //! `compute_config.rs` has the same rule). |
| 24 | //! - `arith_epoch_pinned_bytes`: a fixed tiny model and prompt run on the |
| 25 | //! reference CPU backend; the SHA-256 of the K/V it writes is pinned next to |
| 26 | //! `KV_ARITH_EPOCH`. A numeric change fails this test until its author bumps |
| 27 | //! the epoch and re-pins both values, which changes every namespace id. |
| 28 | |
| 29 | use aien_abi_core::{Llama3RopeScaling, ModelConfig}; |
| 30 | use aien_inference_abi::{ |
| 31 | f32_to_bf16_bits, AienInferenceBackend, DecodeOutput, KvDType, KvPoolConfig, |
| 32 | NativeTransformerBackend, ReferenceCpuBackend, SamplingParams, ScheduledBatch, SequenceRequest, |
| 33 | TransformerWeights, KV_ARITH_EPOCH, |
| 34 | }; |
| 35 | use aien_kv_cache::create_shared_kv_manager_with_pool; |
| 36 | use aien_kv_store::{BackendFormat, KvDtype, LayoutStrides}; |
| 37 | use aien_runtime::compute_config::{ |
| 38 | compute_config_from, HostEngineIdentity, ModelBinding, StoreInputs, |
| 39 | }; |
| 40 | use sha2::{Digest, Sha256}; |
| 41 | use std::collections::HashMap; |
| 42 | use std::sync::Arc; |
| 43 | |
| 44 | const ARITH_ID: &str = "ReferenceCpuBackend"; |
| 45 | |
| 46 | fn base() -> ModelConfig { |
| 47 | ModelConfig { |
| 48 | model_id: "tiny-test".to_string(), |
| 49 | max_sequence_length: 2048, |
| 50 | block_size: 16, |
| 51 | num_layers: 2, |
| 52 | num_heads: 4, |
| 53 | head_dim: 16, |
| 54 | num_kv_heads: 2, |
| 55 | hidden_dim: 64, |
| 56 | intermediate_dim: 128, |
| 57 | vocab_size: 256, |
| 58 | rms_norm_eps: 1e-5, |
| 59 | rope_theta: 10000.0, |
| 60 | rope_scaling: Some(Llama3RopeScaling { |
| 61 | factor: 8.0, |
| 62 | low_freq_factor: 1.0, |
| 63 | high_freq_factor: 4.0, |
| 64 | original_max_position_embeddings: 8192, |
| 65 | }), |
| 66 | tie_word_embeddings: false, |
| 67 | eos_token_ids: vec![2], |
| 68 | qk_norm: false, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn store() -> StoreInputs<'static> { |
| 73 | StoreInputs { |
| 74 | model_sha256: [0xAB; 32], |
| 75 | model_digest_kind: "sha256-file", |
| 76 | dtype: KvDtype::Bf16, |
| 77 | layout: LayoutStrides { |
| 78 | head_stride: 32, |
| 79 | token_stride: 64, |
| 80 | kv_plane_stride: 1024, |
| 81 | layer_stride: 2048, |
| 82 | block_stride: 4096, |
| 83 | element_bytes: 2, |
| 84 | }, |
| 85 | backend_format: BackendFormat::HostPagedPoolV1, |
| 86 | chunk_tokens: 256, |
| 87 | sharing_namespace: "default", |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// (compute digest, namespace id) for a config. |
| 92 | fn ids(cfg: &ModelConfig, arith_id: &str) -> ([u8; 32], [u8; 32]) { |
| 93 | let binding = ModelBinding::from_model(cfg, arith_id).expect("binding"); |
| 94 | let digest = binding.compute.digest().expect("digest"); |
| 95 | let engine = HostEngineIdentity::reference(arith_id).expect("engine identity"); |
| 96 | let fields = binding |
| 97 | .namespace_fields(&store(), &engine.identity()) |
| 98 | .expect("fields"); |
| 99 | assert_eq!( |
| 100 | fields.compute_config_digest, |
| 101 | binding |
| 102 | .compute |
| 103 | .digest_with_engine(&engine.identity()) |
| 104 | .expect("bound digest"), |
| 105 | "compute config plus engine identity is field 14" |
| 106 | ); |
| 107 | (digest, fields.namespace_id().expect("namespace").0) |
| 108 | } |
| 109 | |
| 110 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 111 | enum Effect { |
| 112 | /// In the compute-config digest (ADR 1.2.1 table); the namespace id moves too. |
| 113 | Digest, |
| 114 | /// Carried by namespace fields 4 to 8; the digest does not move. |
| 115 | NamespaceOnly, |
| 116 | /// Written exclusion (ADR 1.2.1 "Fields not listed and why"): neither moves. |
| 117 | Excluded, |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn modelconfig_field_mutation_changes_compute_digest() { |
| 122 | let b = base(); |
| 123 | // Exhaustive: no `..`. A new ModelConfig field fails to compile here. |
| 124 | let ModelConfig { |
| 125 | model_id, |
| 126 | max_sequence_length, |
| 127 | block_size, |
| 128 | num_layers, |
| 129 | num_heads, |
| 130 | head_dim, |
| 131 | num_kv_heads, |
| 132 | hidden_dim, |
| 133 | intermediate_dim, |
| 134 | vocab_size, |
| 135 | rms_norm_eps, |
| 136 | rope_theta, |
| 137 | rope_scaling, |
| 138 | tie_word_embeddings, |
| 139 | eos_token_ids, |
| 140 | qk_norm, |
| 141 | } = b.clone(); |
| 142 | let scaling = rope_scaling.expect("base has llama3 scaling"); |
| 143 | |
| 144 | type Mutation = (&'static str, Effect, Box<dyn Fn(&mut ModelConfig)>); |
| 145 | let mut cases: Vec<Mutation> = vec![ |
| 146 | ("model_id", Effect::NamespaceOnly, { |
| 147 | let v = format!("{model_id}-x"); |
| 148 | Box::new(move |c| c.model_id = v.clone()) |
| 149 | }), |
| 150 | ("max_sequence_length", Effect::Excluded, { |
| 151 | Box::new(move |c| c.max_sequence_length = max_sequence_length * 2) |
| 152 | }), |
| 153 | ("block_size", Effect::NamespaceOnly, { |
| 154 | Box::new(move |c| c.block_size = block_size * 2) |
| 155 | }), |
| 156 | ("num_layers", Effect::NamespaceOnly, { |
| 157 | Box::new(move |c| c.num_layers = num_layers + 1) |
| 158 | }), |
| 159 | ("num_heads", Effect::Digest, { |
| 160 | Box::new(move |c| c.num_heads = num_heads + 1) |
| 161 | }), |
| 162 | ("head_dim", Effect::NamespaceOnly, { |
| 163 | Box::new(move |c| c.head_dim = head_dim + 1) |
| 164 | }), |
| 165 | ("num_kv_heads", Effect::NamespaceOnly, { |
| 166 | Box::new(move |c| c.num_kv_heads = num_kv_heads + 1) |
| 167 | }), |
| 168 | ("hidden_dim", Effect::Digest, { |
| 169 | Box::new(move |c| c.hidden_dim = hidden_dim + 1) |
| 170 | }), |
| 171 | ("intermediate_dim", Effect::Digest, { |
| 172 | Box::new(move |c| c.intermediate_dim = intermediate_dim + 1) |
| 173 | }), |
| 174 | ("vocab_size", Effect::Digest, { |
| 175 | Box::new(move |c| c.vocab_size = vocab_size + 1) |
| 176 | }), |
| 177 | ("rms_norm_eps", Effect::Digest, { |
| 178 | Box::new(move |c| c.rms_norm_eps = rms_norm_eps / 10.0) |
| 179 | }), |
| 180 | ("rope_theta", Effect::NamespaceOnly, { |
| 181 | Box::new(move |c| c.rope_theta = rope_theta * 2.0) |
| 182 | }), |
| 183 | ("rope_scaling (removed)", Effect::NamespaceOnly, { |
| 184 | Box::new(|c| c.rope_scaling = None) |
| 185 | }), |
| 186 | ("rope_scaling.factor", Effect::NamespaceOnly, { |
| 187 | Box::new(move |c| { |
| 188 | c.rope_scaling = Some(Llama3RopeScaling { |
| 189 | factor: scaling.factor + 1.0, |
| 190 | ..scaling |
| 191 | }) |
| 192 | }) |
| 193 | }), |
| 194 | ("rope_scaling.low_freq_factor", Effect::NamespaceOnly, { |
| 195 | Box::new(move |c| { |
| 196 | c.rope_scaling = Some(Llama3RopeScaling { |
| 197 | low_freq_factor: scaling.low_freq_factor + 1.0, |
| 198 | ..scaling |
| 199 | }) |
| 200 | }) |
| 201 | }), |
| 202 | ("rope_scaling.high_freq_factor", Effect::NamespaceOnly, { |
| 203 | Box::new(move |c| { |
| 204 | c.rope_scaling = Some(Llama3RopeScaling { |
| 205 | high_freq_factor: scaling.high_freq_factor + 1.0, |
| 206 | ..scaling |
| 207 | }) |
| 208 | }) |
| 209 | }), |
| 210 | ( |
| 211 | "rope_scaling.original_max_position_embeddings", |
| 212 | Effect::NamespaceOnly, |
| 213 | Box::new(move |c| { |
| 214 | c.rope_scaling = Some(Llama3RopeScaling { |
| 215 | original_max_position_embeddings: scaling.original_max_position_embeddings + 1, |
| 216 | ..scaling |
| 217 | }) |
| 218 | }), |
| 219 | ), |
| 220 | ("tie_word_embeddings", Effect::Digest, { |
| 221 | Box::new(move |c| c.tie_word_embeddings = !tie_word_embeddings) |
| 222 | }), |
| 223 | ("eos_token_ids", Effect::Excluded, { |
| 224 | let mut v = eos_token_ids.clone(); |
| 225 | v.push(99); |
| 226 | Box::new(move |c| c.eos_token_ids = v.clone()) |
| 227 | }), |
| 228 | ("qk_norm", Effect::NamespaceOnly, { |
| 229 | Box::new(move |c| c.qk_norm = !qk_norm) |
| 230 | }), |
| 231 | ]; |
| 232 | // Every ModelConfig field name appears in the table (the destructure above |
| 233 | // guarantees the list of names is complete; this guards the table). |
| 234 | for field in [ |
| 235 | "model_id", |
| 236 | "max_sequence_length", |
| 237 | "block_size", |
| 238 | "num_layers", |
| 239 | "num_heads", |
| 240 | "head_dim", |
| 241 | "num_kv_heads", |
| 242 | "hidden_dim", |
| 243 | "intermediate_dim", |
| 244 | "vocab_size", |
| 245 | "rms_norm_eps", |
| 246 | "rope_theta", |
| 247 | "rope_scaling (removed)", |
| 248 | "tie_word_embeddings", |
| 249 | "eos_token_ids", |
| 250 | "qk_norm", |
| 251 | ] { |
| 252 | assert!( |
| 253 | cases.iter().any(|c| c.0 == field), |
| 254 | "no mutation for {field}" |
| 255 | ); |
| 256 | } |
| 257 | |
| 258 | let (base_digest, base_ns) = ids(&b, ARITH_ID); |
| 259 | for (name, effect, mutate) in cases.drain(..) { |
| 260 | let mut c = b.clone(); |
| 261 | mutate(&mut c); |
| 262 | assert_ne!(c, b, "{name}: the mutation did not change the config"); |
| 263 | let (digest, ns) = ids(&c, ARITH_ID); |
| 264 | match effect { |
| 265 | Effect::Digest => { |
| 266 | assert_ne!(digest, base_digest, "{name} must change the compute digest"); |
| 267 | assert_ne!(ns, base_ns, "{name} must change the namespace id"); |
| 268 | } |
| 269 | Effect::NamespaceOnly => { |
| 270 | assert_eq!(digest, base_digest, "{name} is not a compute-digest field"); |
| 271 | assert_ne!(ns, base_ns, "{name} must change the namespace id"); |
| 272 | } |
| 273 | Effect::Excluded => { |
| 274 | assert_eq!(digest, base_digest, "{name} is written-excluded"); |
| 275 | assert_eq!(ns, base_ns, "{name} is written-excluded"); |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn arith_identity_and_epoch_change_the_compute_digest() { |
| 283 | let b = base(); |
| 284 | let (d0, n0) = ids(&b, ARITH_ID); |
| 285 | let (d1, n1) = ids(&b, "NativeCpuBackend (Rayon Multi-Core)"); |
| 286 | assert_ne!(d0, d1, "a different tensor backend is a different digest"); |
| 287 | assert_ne!(n0, n1); |
| 288 | let mut cc = compute_config_from(&b, ARITH_ID).unwrap(); |
| 289 | assert_eq!( |
| 290 | cc.arith_epoch, KV_ARITH_EPOCH, |
| 291 | "the epoch comes from the constant" |
| 292 | ); |
| 293 | let before = cc.digest().unwrap(); |
| 294 | cc.arith_epoch += 1; |
| 295 | assert_ne!( |
| 296 | cc.digest().unwrap(), |
| 297 | before, |
| 298 | "bumping the epoch changes the digest" |
| 299 | ); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn conversion_refuses_values_that_do_not_fit_the_wire_width() { |
| 304 | let mut c = base(); |
| 305 | // 2^32 heads cannot be written as the u32 of ADR 1.2.1 field 1. |
| 306 | c.num_heads = u32::MAX as usize + 1; |
| 307 | assert!(compute_config_from(&c, ARITH_ID).is_err()); |
| 308 | let mut c = base(); |
| 309 | c.num_layers = u32::MAX as usize + 1; |
| 310 | assert!(ModelBinding::from_model(&c, ARITH_ID).is_err()); |
| 311 | } |
| 312 | |
| 313 | // --- arith_epoch_pinned_bytes ------------------------------------------------ |
| 314 | |
| 315 | /// The epoch the pin below was taken at, and the SHA-256 of the K/V bytes. |
| 316 | const PINNED_EPOCH: u32 = 2; |
| 317 | const PINNED_KV_SHA256: &str = "48340604c2513464fde46789d95b2473e87fdb057201822ff207b5e1acf4872c"; |
| 318 | |
| 319 | fn pin_model() -> ModelConfig { |
| 320 | ModelConfig { |
| 321 | num_layers: 2, |
| 322 | num_heads: 4, |
| 323 | num_kv_heads: 2, |
| 324 | head_dim: 16, |
| 325 | hidden_dim: 64, |
| 326 | intermediate_dim: 128, |
| 327 | vocab_size: 256, |
| 328 | block_size: 16, |
| 329 | ..Default::default() |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | /// Runs the fixed prompt on the reference backend in a bf16 pool (the daemon's |
| 334 | /// pool dtype) and hashes every written K and V value as bf16 bits, in |
| 335 | /// (layer, position, K then V) order. |
| 336 | async fn kv_bytes_sha256() -> String { |
| 337 | let cfg = pin_model(); |
| 338 | let pool = KvPoolConfig::for_model( |
| 339 | 16, |
| 340 | 16, |
| 341 | cfg.num_layers, |
| 342 | cfg.num_kv_heads, |
| 343 | cfg.head_dim, |
| 344 | KvDType::Bf16, |
| 345 | ); |
| 346 | let kv = create_shared_kv_manager_with_pool(16, 16, pool).expect("pool"); |
| 347 | let mut backend = NativeTransformerBackend::with_shared_kv_and_backend( |
| 348 | TransformerWeights::reference_test_weights(&cfg), |
| 349 | Arc::new(ReferenceCpuBackend::new()), |
| 350 | kv.clone(), |
| 351 | ); |
| 352 | let id = 0x1_0000_0001u64; |
| 353 | let prompt: Vec<u32> = (0..40u32).map(|i| (i * 37 + 11) % 253 + 3).collect(); |
| 354 | let prefill = ScheduledBatch { |
| 355 | prefill_requests: vec![SequenceRequest { |
| 356 | request_id: id, |
| 357 | prompt_tokens: prompt, |
| 358 | sampling_params: SamplingParams { |
| 359 | temperature: 0.0, |
| 360 | top_p: 1.0, |
| 361 | max_tokens: 8, |
| 362 | stop_token_ids: vec![], |
| 363 | }, |
| 364 | arrival_time_ns: 0, |
| 365 | priority: 1, |
| 366 | }], |
| 367 | decode_requests: vec![], |
| 368 | block_tables: HashMap::new(), |
| 369 | step_id: 1, |
| 370 | }; |
| 371 | let (out, _) = backend.execute_step(&prefill).await.unwrap(); |
| 372 | assert!(matches!(out[0], DecodeOutput::Token { .. })); |
| 373 | for step in 2..4 { |
| 374 | let decode = ScheduledBatch { |
| 375 | prefill_requests: vec![], |
| 376 | decode_requests: vec![id], |
| 377 | block_tables: HashMap::new(), |
| 378 | step_id: step, |
| 379 | }; |
| 380 | backend.execute_step(&decode).await.unwrap(); |
| 381 | } |
| 382 | |
| 383 | let r = kv.read(); |
| 384 | let table = r.get_block_table(id).expect("table"); |
| 385 | let pool = r.tensor_pool().expect("pool"); |
| 386 | let kv_dim = cfg.num_kv_heads * cfg.head_dim; |
| 387 | let mut h = Sha256::new(); |
| 388 | for layer in 0..cfg.num_layers { |
| 389 | for pos in 0..table.total_tokens { |
| 390 | let (mut k, mut v) = (vec![0.0f32; kv_dim], vec![0.0f32; kv_dim]); |
| 391 | pool.read_token_kv(table.block_ids[pos / 16], layer, pos % 16, &mut k, &mut v); |
| 392 | for x in k.iter().chain(v.iter()) { |
| 393 | h.update(f32_to_bf16_bits(*x).to_le_bytes()); |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | h.finalize().iter().map(|b| format!("{b:02x}")).collect() |
| 398 | } |
| 399 | |
| 400 | #[tokio::test] |
| 401 | async fn arith_epoch_pinned_bytes() { |
| 402 | let actual = kv_bytes_sha256().await; |
| 403 | assert_eq!( |
| 404 | KV_ARITH_EPOCH, PINNED_EPOCH, |
| 405 | "KV_ARITH_EPOCH changed: re-run, then pin the new epoch and hash together" |
| 406 | ); |
| 407 | assert_eq!( |
| 408 | actual, PINNED_KV_SHA256, |
| 409 | "the forward pass now writes different K/V bytes. If this change is intended, \ |
| 410 | bump KV_ARITH_EPOCH in aien-inference-abi (every stored chunk becomes a different \ |
| 411 | namespace) and pin the new epoch and hash here." |
| 412 | ); |
| 413 | } |
| 414 | |
| 415 | /// sc#504 (ADR 1.2.2): the host reference path fills the engine identity |
| 416 | /// honestly: weights used as the file holds them, a build id naming this |
| 417 | /// crate's version and commit, a rounding class naming the backend and |
| 418 | /// `KV_ARITH_EPOCH`, and a dense engine config with every switch off. |
| 419 | #[test] |
| 420 | fn host_reference_engine_identity_names_backend_epoch_and_build() { |
| 421 | let e = HostEngineIdentity::reference(ARITH_ID).expect("engine identity"); |
| 422 | let id = e.identity(); |
| 423 | assert_eq!(id.weight_format, aien_kv_store::WeightFormat::AsFile); |
| 424 | assert!( |
| 425 | id.engine_build_id |
| 426 | .starts_with(&format!("aien-runtime/{}+git:", env!("CARGO_PKG_VERSION"))), |
| 427 | "build id {:?}", |
| 428 | id.engine_build_id |
| 429 | ); |
| 430 | assert_eq!( |
| 431 | id.rounding_class, |
| 432 | format!("{ARITH_ID}@kv-arith-epoch-{KV_ARITH_EPOCH}") |
| 433 | ); |
| 434 | let dense = aien_kv_store::EngineConfig { |
| 435 | num_experts: 0, |
| 436 | experts_per_token: 0, |
| 437 | expert_intermediate_dim: 0, |
| 438 | whole_prompt_prefill: false, |
| 439 | device_router: false, |
| 440 | matmul_path: "host-tensor-backend", |
| 441 | }; |
| 442 | assert_eq!(id.engine_config_digest, dense.digest().unwrap()); |
| 443 | // Another backend is another rounding class. |
| 444 | let other = HostEngineIdentity::reference("NativeCpuBackend (Rayon Multi-Core)").unwrap(); |
| 445 | assert_ne!(other.identity().rounding_class, id.rounding_class); |
| 446 | } |
| 447 | |
| 448 | /// Each engine input changed alone moves the namespace bound by |
| 449 | /// `ModelBinding::namespace_fields` (the daemon path). |
| 450 | #[test] |
| 451 | fn each_engine_input_changes_the_bound_namespace() { |
| 452 | let b = base(); |
| 453 | let binding = ModelBinding::from_model(&b, ARITH_ID).expect("binding"); |
| 454 | let host = HostEngineIdentity::reference(ARITH_ID).expect("engine identity"); |
| 455 | let ns = |e: &aien_kv_store::EngineIdentity| { |
| 456 | binding |
| 457 | .namespace_fields(&store(), e) |
| 458 | .expect("fields") |
| 459 | .namespace_id() |
| 460 | .expect("namespace") |
| 461 | }; |
| 462 | let base_ns = ns(&host.identity()); |
| 463 | let mut wf = host.identity(); |
| 464 | wf.weight_format = aien_kv_store::WeightFormat::Fp8All; |
| 465 | let mut build = host.identity(); |
| 466 | build.engine_build_id = "aien-runtime/0.0.0+git:other"; |
| 467 | let mut round = host.identity(); |
| 468 | round.rounding_class = "ReferenceCpuBackend@kv-arith-epoch-999"; |
| 469 | let mut cfg = host.identity(); |
| 470 | cfg.engine_config_digest[0] ^= 1; |
| 471 | let mut seen = vec![base_ns]; |
| 472 | for (name, e) in [ |
| 473 | ("weight_format", wf), |
| 474 | ("engine_build_id", build), |
| 475 | ("rounding_class", round), |
| 476 | ("engine_config_digest", cfg), |
| 477 | ] { |
| 478 | let got = ns(&e); |
| 479 | assert!(!seen.contains(&got), "{name} did not move the namespace"); |
| 480 | seen.push(got); |
| 481 | } |
| 482 | } |