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-kv-store / tests / golden_tests.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 | //! Golden vectors: `tests/golden/kv_record_v1.json`. The file pins the |
| 17 | //! compute-config digest, the namespace derivation, the chunk key chain, the |
| 18 | //! 256-byte header bytes and the 4096-byte header region (segment digest table |
| 19 | //! and root) so the native C implementation (aienos N1) can check itself |
| 20 | //! against the same file (CUTS "Pin"). Regenerate deliberately with |
| 21 | //! `AIEN_KV_REGEN_GOLDEN=1 cargo test -p aien-kv-store --test golden_tests regenerate_golden`; |
| 22 | //! then bump `tests/golden/README.md` and the aienos `CONTRACT.lock`. |
| 23 | |
| 24 | mod common; |
| 25 | |
| 26 | use aien_kv_store::{ |
| 27 | chunk_chain, validate_record, BackendFormat, ChunkKey, ComputeConfig, EngineConfig, |
| 28 | EngineIdentity, HiddenAct, KvDtype, LayoutStrides, NamespaceFields, RecordHeader, RopeScaling, |
| 29 | WeightFormat, |
| 30 | }; |
| 31 | use common::*; |
| 32 | use serde_json::{json, Value}; |
| 33 | use sha2::{Digest, Sha256}; |
| 34 | |
| 35 | const GOLDEN: &str = concat!( |
| 36 | env!("CARGO_MANIFEST_DIR"), |
| 37 | "/tests/golden/kv_record_v1.json" |
| 38 | ); |
| 39 | |
| 40 | fn cc_to_json(c: &ComputeConfig) -> Value { |
| 41 | json!({ |
| 42 | "num_heads": c.num_heads, |
| 43 | "hidden_dim": c.hidden_dim, |
| 44 | "intermediate_dim": c.intermediate_dim, |
| 45 | "vocab_size": c.vocab_size, |
| 46 | "rms_norm_eps_f32_bits": c.rms_norm_eps.to_bits(), |
| 47 | "tie_word_embeddings": c.tie_word_embeddings, |
| 48 | "hidden_act": c.hidden_act as u8, |
| 49 | "arith_id": c.arith_id, |
| 50 | "arith_epoch": c.arith_epoch, |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | fn parse_cc(v: &Value) -> ComputeConfig<'_> { |
| 55 | assert_eq!(u(v, "hidden_act"), 1, "only silu exists"); |
| 56 | ComputeConfig { |
| 57 | num_heads: u(v, "num_heads") as u32, |
| 58 | hidden_dim: u(v, "hidden_dim"), |
| 59 | intermediate_dim: u(v, "intermediate_dim"), |
| 60 | vocab_size: u(v, "vocab_size"), |
| 61 | rms_norm_eps: f32::from_bits(u(v, "rms_norm_eps_f32_bits") as u32), |
| 62 | tie_word_embeddings: v["tie_word_embeddings"].as_bool().unwrap(), |
| 63 | hidden_act: HiddenAct::Silu, |
| 64 | arith_id: v["arith_id"].as_str().unwrap(), |
| 65 | arith_epoch: u(v, "arith_epoch") as u32, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn ec_to_json(c: &EngineConfig) -> Value { |
| 70 | json!({ |
| 71 | "num_experts": c.num_experts, |
| 72 | "experts_per_token": c.experts_per_token, |
| 73 | "expert_intermediate_dim": c.expert_intermediate_dim, |
| 74 | "whole_prompt_prefill": c.whole_prompt_prefill, |
| 75 | "device_router": c.device_router, |
| 76 | "matmul_path": c.matmul_path, |
| 77 | }) |
| 78 | } |
| 79 | |
| 80 | fn parse_ec(v: &Value) -> EngineConfig<'_> { |
| 81 | EngineConfig { |
| 82 | num_experts: u(v, "num_experts") as u32, |
| 83 | experts_per_token: u(v, "experts_per_token") as u32, |
| 84 | expert_intermediate_dim: u(v, "expert_intermediate_dim"), |
| 85 | whole_prompt_prefill: v["whole_prompt_prefill"].as_bool().unwrap(), |
| 86 | device_router: v["device_router"].as_bool().unwrap(), |
| 87 | matmul_path: v["matmul_path"].as_str().unwrap(), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | fn engine_to_json(e: &EngineIdentity, ec: &EngineConfig) -> Value { |
| 92 | assert_eq!(e.engine_config_digest, ec.digest().unwrap()); |
| 93 | json!({ |
| 94 | "weight_format": e.weight_format as u8, |
| 95 | "weight_format_name": e.weight_format.as_str(), |
| 96 | "engine_build_id": e.engine_build_id, |
| 97 | "rounding_class": e.rounding_class, |
| 98 | "engine_config": ec_to_json(ec), |
| 99 | "engine_config_digest": hex(&e.engine_config_digest), |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | fn parse_engine(v: &Value) -> EngineIdentity<'_> { |
| 104 | EngineIdentity { |
| 105 | weight_format: WeightFormat::from_u8(u(v, "weight_format") as u8).unwrap(), |
| 106 | engine_build_id: v["engine_build_id"].as_str().unwrap(), |
| 107 | rounding_class: v["rounding_class"].as_str().unwrap(), |
| 108 | engine_config_digest: unhex32(v["engine_config_digest"].as_str().unwrap()), |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | fn ns_to_json( |
| 113 | f: &NamespaceFields, |
| 114 | c: &ComputeConfig, |
| 115 | e: &EngineIdentity, |
| 116 | ec: &EngineConfig, |
| 117 | ) -> Value { |
| 118 | json!({ |
| 119 | "model_sha256": hex(&f.model_sha256), |
| 120 | "model_digest_kind": f.model_digest_kind, |
| 121 | "model_id": f.model_id, |
| 122 | "num_layers": f.num_layers, |
| 123 | "num_kv_heads": f.num_kv_heads, |
| 124 | "head_dim": f.head_dim, |
| 125 | "block_size": f.block_size, |
| 126 | "rope_theta_f32_bits": f.rope_theta.to_bits(), |
| 127 | "rope_scaling": f.rope_scaling.map(|r| json!({ |
| 128 | "factor_f64_bits": r.factor.to_bits(), |
| 129 | "low_freq_factor_f64_bits": r.low_freq_factor.to_bits(), |
| 130 | "high_freq_factor_f64_bits": r.high_freq_factor.to_bits(), |
| 131 | "original_max_position_embeddings": r.original_max_position_embeddings, |
| 132 | })), |
| 133 | "qk_norm": f.qk_norm, |
| 134 | "dtype": f.dtype as u8, |
| 135 | "layout": { |
| 136 | "head_stride": f.layout.head_stride, |
| 137 | "token_stride": f.layout.token_stride, |
| 138 | "kv_plane_stride": f.layout.kv_plane_stride, |
| 139 | "layer_stride": f.layout.layer_stride, |
| 140 | "block_stride": f.layout.block_stride, |
| 141 | "element_bytes": f.layout.element_bytes, |
| 142 | }, |
| 143 | "backend_format": f.backend_format as u8, |
| 144 | "chunk_tokens": f.chunk_tokens, |
| 145 | "sharing_namespace": f.sharing_namespace, |
| 146 | "compute_config": cc_to_json(c), |
| 147 | "engine": engine_to_json(e, ec), |
| 148 | "compute_config_digest": hex(&f.compute_config_digest), |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | fn u(v: &Value, k: &str) -> u64 { |
| 153 | v[k].as_u64().unwrap_or_else(|| panic!("missing u64 {k}")) |
| 154 | } |
| 155 | |
| 156 | fn parse_ns(v: &Value) -> NamespaceFields<'_> { |
| 157 | let l = &v["layout"]; |
| 158 | NamespaceFields { |
| 159 | model_sha256: unhex32(v["model_sha256"].as_str().unwrap()), |
| 160 | model_digest_kind: v["model_digest_kind"].as_str().unwrap(), |
| 161 | model_id: v["model_id"].as_str().unwrap(), |
| 162 | num_layers: u(v, "num_layers") as u32, |
| 163 | num_kv_heads: u(v, "num_kv_heads") as u32, |
| 164 | head_dim: u(v, "head_dim") as u32, |
| 165 | block_size: u(v, "block_size") as u32, |
| 166 | rope_theta: f32::from_bits(u(v, "rope_theta_f32_bits") as u32), |
| 167 | rope_scaling: match &v["rope_scaling"] { |
| 168 | Value::Null => None, |
| 169 | r => Some(RopeScaling { |
| 170 | factor: f64::from_bits(u(r, "factor_f64_bits")), |
| 171 | low_freq_factor: f64::from_bits(u(r, "low_freq_factor_f64_bits")), |
| 172 | high_freq_factor: f64::from_bits(u(r, "high_freq_factor_f64_bits")), |
| 173 | original_max_position_embeddings: u(r, "original_max_position_embeddings"), |
| 174 | }), |
| 175 | }, |
| 176 | qk_norm: v["qk_norm"].as_bool().unwrap(), |
| 177 | dtype: KvDtype::from_u8(u(v, "dtype") as u8).unwrap(), |
| 178 | layout: LayoutStrides { |
| 179 | head_stride: u(l, "head_stride"), |
| 180 | token_stride: u(l, "token_stride"), |
| 181 | kv_plane_stride: u(l, "kv_plane_stride"), |
| 182 | layer_stride: u(l, "layer_stride"), |
| 183 | block_stride: u(l, "block_stride"), |
| 184 | element_bytes: u(l, "element_bytes"), |
| 185 | }, |
| 186 | backend_format: BackendFormat::from_u8(u(v, "backend_format") as u8).unwrap(), |
| 187 | chunk_tokens: u(v, "chunk_tokens") as u32, |
| 188 | sharing_namespace: v["sharing_namespace"].as_str().unwrap(), |
| 189 | compute_config_digest: unhex32(v["compute_config_digest"].as_str().unwrap()), |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | fn tokens_of(v: &Value) -> Vec<u32> { |
| 194 | v["tokens"] |
| 195 | .as_array() |
| 196 | .unwrap() |
| 197 | .iter() |
| 198 | .map(|t| t.as_u64().unwrap() as u32) |
| 199 | .collect() |
| 200 | } |
| 201 | |
| 202 | fn written_ns(i: usize) -> u64 { |
| 203 | 1_700_000_000_000_000_000 + i as u64 |
| 204 | } |
| 205 | |
| 206 | /// Derive every output of one vector from its inputs (the library under test). |
| 207 | fn outputs(name: &str, ns_v: &Value, tokens: &[u32]) -> Value { |
| 208 | let f = parse_ns(ns_v); |
| 209 | let ns = f.namespace_id().unwrap(); |
| 210 | let chain = chunk_chain(&ns, f.chunk_tokens, tokens).unwrap(); |
| 211 | let mut chunks = Vec::new(); |
| 212 | for (i, key) in chain.iter().enumerate() { |
| 213 | let start = i * f.chunk_tokens as usize; |
| 214 | let end = (start + f.chunk_tokens as usize).min(tokens.len()); |
| 215 | let parent = if i == 0 { None } else { Some(&chain[i - 1]) }; |
| 216 | let token_count = (end - start) as u32; |
| 217 | let h = f |
| 218 | .chunk_header(&ns, *key, parent, start as u32, token_count, written_ns(i)) |
| 219 | .unwrap(); |
| 220 | let n_seg = f.segment_count(token_count).unwrap(); |
| 221 | let prefix = format!("{name}/{i}"); |
| 222 | let digests = seg_digests(&prefix, n_seg); |
| 223 | let rec = RecordHeader { |
| 224 | chunk: h, |
| 225 | payload_sha256: aien_kv_store::payload_root(&digests), |
| 226 | }; |
| 227 | let region = rec.encode_region(&digests).unwrap(); |
| 228 | chunks.push(json!({ |
| 229 | "index": i, |
| 230 | "first_position": start, |
| 231 | "token_count": end - start, |
| 232 | "parent_key": hex(&h.parent_key), |
| 233 | "chunk_key": hex(key.as_bytes()), |
| 234 | "payload_len": h.payload_len, |
| 235 | "segment_bytes": f.segment_bytes(token_count).unwrap(), |
| 236 | "segment_count": n_seg, |
| 237 | "segment_digests_of_ascii": format!("{prefix}/seg/<j>"), |
| 238 | "segment_digests": digests.iter().map(|d| hex(d)).collect::<Vec<_>>(), |
| 239 | "payload_sha256": hex(&rec.payload_sha256), |
| 240 | "written_unix_ns": h.written_unix_ns, |
| 241 | "header_hex": hex(&rec.encode()), |
| 242 | "region_sha256": hex(&Sha256::digest(region)), |
| 243 | })); |
| 244 | } |
| 245 | json!({ "namespace_id": hex(&ns.0), "chunks": chunks }) |
| 246 | } |
| 247 | |
| 248 | type VectorInput = ( |
| 249 | &'static str, |
| 250 | NamespaceFields<'static>, |
| 251 | ComputeConfig<'static>, |
| 252 | (EngineIdentity<'static>, EngineConfig<'static>), |
| 253 | Vec<u32>, |
| 254 | ); |
| 255 | |
| 256 | fn vector_inputs() -> Vec<VectorInput> { |
| 257 | let mut small_f = sample(); |
| 258 | small_f.block_size = 4; |
| 259 | small_f.chunk_tokens = 8; |
| 260 | small_f.layout = LayoutStrides { |
| 261 | head_stride: 128, |
| 262 | token_stride: 1024, |
| 263 | kv_plane_stride: 4096, |
| 264 | layer_stride: 8192, |
| 265 | block_stride: 131072, |
| 266 | element_bytes: 2, |
| 267 | }; |
| 268 | |
| 269 | let mut native = sample(); |
| 270 | native.model_id = "llama-3.2-1b-instruct-q4km"; |
| 271 | native.model_digest_kind = "sha256-gguf"; |
| 272 | native.rope_scaling = None; |
| 273 | native.dtype = KvDtype::Fp32; |
| 274 | native.backend_format = BackendFormat::NativeF32DecodeStateV1; |
| 275 | native.block_size = 16; |
| 276 | native.chunk_tokens = 64; |
| 277 | native.layout = LayoutStrides { |
| 278 | head_stride: 256, |
| 279 | token_stride: 2048, |
| 280 | kv_plane_stride: 32768, |
| 281 | layer_stride: 65536, |
| 282 | block_stride: 1048576, |
| 283 | element_bytes: 4, |
| 284 | }; |
| 285 | |
| 286 | let mut qk = small_f; |
| 287 | qk.model_id = "qwen3-4b-instruct-2507"; |
| 288 | qk.rope_scaling = None; |
| 289 | qk.qk_norm = true; |
| 290 | qk.sharing_namespace = ""; |
| 291 | |
| 292 | let llama = sample_compute(); |
| 293 | let qwen = ComputeConfig { |
| 294 | num_heads: 32, |
| 295 | hidden_dim: 2560, |
| 296 | intermediate_dim: 9728, |
| 297 | vocab_size: 151_936, |
| 298 | rms_norm_eps: 1e-6, |
| 299 | tie_word_embeddings: true, |
| 300 | hidden_act: HiddenAct::Silu, |
| 301 | arith_id: "NativeCpuBackend (Rayon Multi-Core)", |
| 302 | arith_epoch: 1, |
| 303 | }; |
| 304 | let native_cc = ComputeConfig { |
| 305 | arith_id: "aienos-infer-kernel", |
| 306 | ..llama |
| 307 | }; |
| 308 | let eps_1e6 = ComputeConfig { |
| 309 | rms_norm_eps: 1e-6, |
| 310 | ..llama |
| 311 | }; |
| 312 | let epoch_2 = ComputeConfig { |
| 313 | arith_epoch: 2, |
| 314 | ..llama |
| 315 | }; |
| 316 | |
| 317 | let real_tokens: Vec<u32> = (0..300u32).map(|i| (i * 37 + 11) % 128_256).collect(); |
| 318 | let engine = (sample_engine(), sample_engine_config()); |
| 319 | let fp8_experts = ( |
| 320 | EngineIdentity { |
| 321 | weight_format: WeightFormat::Fp8Experts, |
| 322 | ..sample_engine() |
| 323 | }, |
| 324 | sample_engine_config(), |
| 325 | ); |
| 326 | let whole_prompt_cfg = EngineConfig { |
| 327 | whole_prompt_prefill: true, |
| 328 | ..sample_engine_config() |
| 329 | }; |
| 330 | let whole_prompt = ( |
| 331 | EngineIdentity { |
| 332 | engine_config_digest: whole_prompt_cfg.digest().unwrap(), |
| 333 | ..sample_engine() |
| 334 | }, |
| 335 | whole_prompt_cfg, |
| 336 | ); |
| 337 | let with_digest = |
| 338 | |mut f: NamespaceFields<'static>, c: &ComputeConfig, e: &(EngineIdentity, EngineConfig)| { |
| 339 | f.compute_config_digest = c.digest_with_engine(&e.0).unwrap(); |
| 340 | f |
| 341 | }; |
| 342 | vec![ |
| 343 | ( |
| 344 | "host-small-partial-tail", |
| 345 | with_digest(small_f, &llama, &engine), |
| 346 | llama, |
| 347 | engine, |
| 348 | (0..20).collect(), |
| 349 | ), |
| 350 | ( |
| 351 | "host-llama32-1b-full-and-partial", |
| 352 | with_digest(sample(), &llama, &engine), |
| 353 | llama, |
| 354 | engine, |
| 355 | real_tokens, |
| 356 | ), |
| 357 | ( |
| 358 | "native-f32-partial-tail", |
| 359 | with_digest(native, &native_cc, &engine), |
| 360 | native_cc, |
| 361 | engine, |
| 362 | (1000..1070).collect(), |
| 363 | ), |
| 364 | ( |
| 365 | "qk-norm-empty-sharing-one-full-chunk", |
| 366 | with_digest(qk, &qwen, &engine), |
| 367 | qwen, |
| 368 | engine, |
| 369 | (50..58).collect(), |
| 370 | ), |
| 371 | // Review finding 1: identical to `host-small-partial-tail` except |
| 372 | // rms_norm_eps (1e-5 there, 1e-6 here); the namespace id must differ. |
| 373 | ( |
| 374 | "rms-norm-eps-1e-6-only", |
| 375 | with_digest(small_f, &eps_1e6, &engine), |
| 376 | eps_1e6, |
| 377 | engine, |
| 378 | (0..20).collect(), |
| 379 | ), |
| 380 | // Identical to `host-small-partial-tail` except arith_epoch 2. |
| 381 | ( |
| 382 | "arith-epoch-2", |
| 383 | with_digest(small_f, &epoch_2, &engine), |
| 384 | epoch_2, |
| 385 | engine, |
| 386 | (0..20).collect(), |
| 387 | ), |
| 388 | // sc#504: identical to `host-small-partial-tail` except the weight |
| 389 | // format as loaded (same file, fp8 experts). |
| 390 | ( |
| 391 | "weight-format-fp8-experts-only", |
| 392 | with_digest(small_f, &llama, &fp8_experts), |
| 393 | llama, |
| 394 | fp8_experts, |
| 395 | (0..20).collect(), |
| 396 | ), |
| 397 | // sc#504: identical except the whole-prompt prefill switch of the |
| 398 | // engine config (it changes activation rounding). |
| 399 | ( |
| 400 | "whole-prompt-prefill-only", |
| 401 | with_digest(small_f, &llama, &whole_prompt), |
| 402 | llama, |
| 403 | whole_prompt, |
| 404 | (0..20).collect(), |
| 405 | ), |
| 406 | ] |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn regenerate_golden() { |
| 411 | if std::env::var("AIEN_KV_REGEN_GOLDEN").as_deref() != Ok("1") { |
| 412 | return; |
| 413 | } |
| 414 | let vectors: Vec<Value> = vector_inputs() |
| 415 | .into_iter() |
| 416 | .map(|(name, f, c, (e, ec), tokens)| { |
| 417 | let ns_v = ns_to_json(&f, &c, &e, &ec); |
| 418 | let out = outputs(name, &ns_v, &tokens); |
| 419 | json!({ |
| 420 | "name": name, |
| 421 | "namespace": ns_v, |
| 422 | "tokens": tokens, |
| 423 | "expected": out, |
| 424 | }) |
| 425 | }) |
| 426 | .collect(); |
| 427 | let doc = json!({ |
| 428 | "format_version": 1, |
| 429 | "about": "ADR 0003 sections 1 (1.2.2, sc#504), 2.1 and 12 (C1b). engine_config_digest = SHA-256('AIEN-PKV-ENG-V1\\0' || num_experts u32le || experts_per_token u32le || expert_intermediate_dim u64le || whole_prompt_prefill u8 || device_router u8 || matmul_path u8-len + bytes); compute_config_digest (field 14) = SHA-256('AIEN-PKV-CFG-V2\\0' || num_heads u32le || hidden_dim u64le || intermediate_dim u64le || vocab_size u64le || rms_norm_eps f32 bits u32le || tie u8 || hidden_act u8 || arith_id u8-len + bytes || arith_epoch u32le || weight_format u8 (1 as-file, 2 bf16, 3 fp8-experts, 4 fp8-all) || engine_build_id u8-len + bytes || rounding_class u8-len + bytes || engine_config_digest); namespace_id = SHA-256('AIEN-PKV-NS-V2\\0' || fields 1 to 13 || compute_config_digest); chunk_key = SHA-256('AIEN-PKV-CHUNK-V1\\0' || namespace_id || parent_key || first_position u32le || token_count u32le || tokens u32le). header_hex is the 256-byte record header; the record file starts with a 4096-byte region = header_hex || segment digests (32 bytes each, segment_count of them) || zeros; the payload starts at file offset 4096. payload_sha256 = SHA-256('AIEN-PKV-PAYLOAD-V1\\0' || segment digests). Segment digests are SHA-256 of the ASCII string segment_digests_of_ascii with <j> replaced by the segment index. region_sha256 is the SHA-256 of the whole 4096-byte region. f32/f64 inputs are given as IEEE bit patterns.", |
| 430 | "vectors": vectors, |
| 431 | }); |
| 432 | let mut text = serde_json::to_string_pretty(&doc).unwrap(); |
| 433 | text.push('\n'); |
| 434 | std::fs::write(GOLDEN, text).unwrap(); |
| 435 | } |
| 436 | |
| 437 | fn golden() -> Value { |
| 438 | let text = std::fs::read_to_string(GOLDEN).expect("golden file present"); |
| 439 | serde_json::from_str(&text).unwrap() |
| 440 | } |
| 441 | |
| 442 | #[test] |
| 443 | fn identity_vectors_match_golden() { |
| 444 | let doc = golden(); |
| 445 | assert_eq!(doc["format_version"], 1); |
| 446 | let vectors = doc["vectors"].as_array().unwrap(); |
| 447 | assert!( |
| 448 | vectors.len() >= 8, |
| 449 | "golden file must carry the six vectors of C1b and the two engine vectors of sc#504" |
| 450 | ); |
| 451 | let mut checked_headers = 0; |
| 452 | for v in vectors { |
| 453 | let name = v["name"].as_str().unwrap(); |
| 454 | let tokens = tokens_of(v); |
| 455 | let got = outputs(name, &v["namespace"], &tokens); |
| 456 | assert_eq!( |
| 457 | got["namespace_id"], v["expected"]["namespace_id"], |
| 458 | "{name}: namespace_id" |
| 459 | ); |
| 460 | let want_chunks = v["expected"]["chunks"].as_array().unwrap(); |
| 461 | let got_chunks = got["chunks"].as_array().unwrap(); |
| 462 | assert!(!want_chunks.is_empty(), "{name}: no chunks"); |
| 463 | assert_eq!( |
| 464 | got_chunks, want_chunks, |
| 465 | "{name}: chunk keys, header bytes or region differ" |
| 466 | ); |
| 467 | |
| 468 | // The stored bytes decode back to the same fields and validate. |
| 469 | let f = parse_ns(&v["namespace"]); |
| 470 | let ns = f.namespace_id().unwrap(); |
| 471 | for c in want_chunks { |
| 472 | let bytes = unhex(c["header_hex"].as_str().unwrap()); |
| 473 | let rec = RecordHeader::decode_struct(&bytes).unwrap(); |
| 474 | assert_eq!( |
| 475 | rec.encode().as_slice(), |
| 476 | bytes.as_slice(), |
| 477 | "{name}: re-encode" |
| 478 | ); |
| 479 | assert_eq!(rec.chunk.namespace_id, ns); |
| 480 | assert_eq!( |
| 481 | rec.chunk.chunk_key, |
| 482 | ChunkKey(aien_platform::ObjectId(unhex32( |
| 483 | c["chunk_key"].as_str().unwrap() |
| 484 | ))) |
| 485 | ); |
| 486 | let digests: Vec<[u8; 32]> = c["segment_digests"] |
| 487 | .as_array() |
| 488 | .unwrap() |
| 489 | .iter() |
| 490 | .map(|d| unhex32(d.as_str().unwrap())) |
| 491 | .collect(); |
| 492 | assert_eq!(digests.len() as u64, u(c, "segment_count")); |
| 493 | let region = rec.encode_region(&digests).unwrap(); |
| 494 | assert_eq!( |
| 495 | hex(&Sha256::digest(region)), |
| 496 | c["region_sha256"].as_str().unwrap(), |
| 497 | "{name}: region bytes" |
| 498 | ); |
| 499 | let file_size = 4096 + c["payload_len"].as_u64().unwrap(); |
| 500 | validate_record(®ion, file_size, &rec.chunk, u(c, "segment_bytes")).unwrap(); |
| 501 | checked_headers += 1; |
| 502 | } |
| 503 | } |
| 504 | assert!(checked_headers >= 12); |
| 505 | } |
| 506 | |
| 507 | #[test] |
| 508 | fn golden_vectors_include_compute_config_digest() { |
| 509 | let doc = golden(); |
| 510 | let vectors = doc["vectors"].as_array().unwrap(); |
| 511 | assert!(vectors.len() >= 8); |
| 512 | for v in vectors { |
| 513 | let name = v["name"].as_str().unwrap(); |
| 514 | let ns_v = &v["namespace"]; |
| 515 | // All nine inputs and the digest are present and consistent. |
| 516 | let cc_v = &ns_v["compute_config"]; |
| 517 | for k in [ |
| 518 | "num_heads", |
| 519 | "hidden_dim", |
| 520 | "intermediate_dim", |
| 521 | "vocab_size", |
| 522 | "rms_norm_eps_f32_bits", |
| 523 | "tie_word_embeddings", |
| 524 | "hidden_act", |
| 525 | "arith_id", |
| 526 | "arith_epoch", |
| 527 | ] { |
| 528 | assert!(!cc_v[k].is_null(), "{name}: compute_config.{k} missing"); |
| 529 | } |
| 530 | let cc = parse_cc(cc_v); |
| 531 | let engine = parse_engine(&ns_v["engine"]); |
| 532 | let ec = parse_ec(&ns_v["engine"]["engine_config"]); |
| 533 | assert_eq!( |
| 534 | hex(&ec.digest().unwrap()), |
| 535 | ns_v["engine"]["engine_config_digest"].as_str().unwrap(), |
| 536 | "{name}: engine config digest" |
| 537 | ); |
| 538 | let digest = hex(&cc.digest_with_engine(&engine).unwrap()); |
| 539 | assert_eq!( |
| 540 | ns_v["compute_config_digest"].as_str().unwrap(), |
| 541 | digest, |
| 542 | "{name}: digest" |
| 543 | ); |
| 544 | // And it is what the namespace id commits to. |
| 545 | let f = parse_ns(ns_v); |
| 546 | let mut other = f; |
| 547 | other.compute_config_digest[0] ^= 1; |
| 548 | assert_ne!( |
| 549 | f.namespace_id().unwrap(), |
| 550 | other.namespace_id().unwrap(), |
| 551 | "{name}: namespace ignores the digest" |
| 552 | ); |
| 553 | } |
| 554 | // The two new vectors differ from their sibling in exactly one field. |
| 555 | let by_name = |n: &str| vectors.iter().find(|v| v["name"] == n).unwrap(); |
| 556 | let base = by_name("host-small-partial-tail"); |
| 557 | for (sibling, field_bits) in [ |
| 558 | ("rms-norm-eps-1e-6-only", "rms_norm_eps_f32_bits"), |
| 559 | ("arith-epoch-2", "arith_epoch"), |
| 560 | ] { |
| 561 | let s = by_name(sibling); |
| 562 | assert_eq!(base["tokens"], s["tokens"], "{sibling}: same tokens"); |
| 563 | assert_ne!( |
| 564 | base["expected"]["namespace_id"], s["expected"]["namespace_id"], |
| 565 | "{sibling}: namespace must differ" |
| 566 | ); |
| 567 | let mut a = base["namespace"].clone(); |
| 568 | let mut b = s["namespace"].clone(); |
| 569 | assert_ne!( |
| 570 | a["compute_config"][field_bits], |
| 571 | b["compute_config"][field_bits] |
| 572 | ); |
| 573 | for side in [&mut a, &mut b] { |
| 574 | side["compute_config"][field_bits] = Value::Null; |
| 575 | side["compute_config_digest"] = Value::Null; |
| 576 | } |
| 577 | assert_eq!( |
| 578 | a, b, |
| 579 | "{sibling}: differs from the base in {field_bits} only" |
| 580 | ); |
| 581 | } |
| 582 | assert_eq!( |
| 583 | u( |
| 584 | &by_name("host-small-partial-tail")["namespace"]["compute_config"], |
| 585 | "rms_norm_eps_f32_bits" |
| 586 | ), |
| 587 | u64::from(1e-5f32.to_bits()) |
| 588 | ); |
| 589 | assert_eq!( |
| 590 | u( |
| 591 | &by_name("rms-norm-eps-1e-6-only")["namespace"]["compute_config"], |
| 592 | "rms_norm_eps_f32_bits" |
| 593 | ), |
| 594 | u64::from(1e-6f32.to_bits()) |
| 595 | ); |
| 596 | } |
| 597 | |
| 598 | /// sc#504: the two engine vectors differ from `host-small-partial-tail` in one |
| 599 | /// engine input only, and their namespace ids differ. |
| 600 | #[test] |
| 601 | fn golden_engine_vectors_differ_in_one_engine_field_only() { |
| 602 | let doc = golden(); |
| 603 | let vectors = doc["vectors"].as_array().unwrap(); |
| 604 | let by_name = |n: &str| vectors.iter().find(|v| v["name"] == n).unwrap(); |
| 605 | let base = by_name("host-small-partial-tail"); |
| 606 | for (sibling, path) in [ |
| 607 | ("weight-format-fp8-experts-only", &["weight_format"][..]), |
| 608 | ( |
| 609 | "whole-prompt-prefill-only", |
| 610 | &["engine_config", "whole_prompt_prefill"][..], |
| 611 | ), |
| 612 | ] { |
| 613 | let s = by_name(sibling); |
| 614 | assert_eq!(base["tokens"], s["tokens"], "{sibling}: same tokens"); |
| 615 | assert_ne!( |
| 616 | base["expected"]["namespace_id"], s["expected"]["namespace_id"], |
| 617 | "{sibling}: namespace must differ" |
| 618 | ); |
| 619 | let mut a = base["namespace"].clone(); |
| 620 | let mut b = s["namespace"].clone(); |
| 621 | for side in [&mut a, &mut b] { |
| 622 | let mut node = &mut side["engine"]; |
| 623 | for k in path { |
| 624 | node = &mut node[*k]; |
| 625 | } |
| 626 | *node = Value::Null; |
| 627 | side["engine"]["weight_format_name"] = Value::Null; |
| 628 | side["engine"]["engine_config_digest"] = Value::Null; |
| 629 | side["compute_config_digest"] = Value::Null; |
| 630 | } |
| 631 | assert_eq!(a, b, "{sibling}: differs from the base in {path:?} only"); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// The 256-byte struct of C1 (commit ce5d9eb, vector |
| 636 | /// `qk-norm-empty-sharing-one-full-chunk` chunk 0). C1b keeps offsets 0 to 255 |
| 637 | /// as they were: only values derived from the changed identity differ. |
| 638 | const C1_QK_HEADER_HEX: &str = "4149454e4b56433101000100000100009f3ad00ef5e5a019509358ca17af031787ea605b2125adf9f45b45e68d79e77439892035cb1a28bc34e635299fa3952ce55337971cd47d0b15b2decf435611c40000000000000000000000000000000000000000000000000000000000000000abababababababababababababababababababababababababababababababab00000000080000000800000004000000100000000800000040000000030100000000040000000000937b24a1e2f3d11364ae69717aa6511bcdef9beea2569b40a3f7d3403bd80fe000002a36fe9c9717da902ce1dc4828ae671e228f2cf4439b6320f39c5b3f5143c842a0077f2af6c9"; |
| 639 | |
| 640 | #[test] |
| 641 | fn header_struct_bytes_0_to_255_unchanged_by_the_region() { |
| 642 | let doc = golden(); |
| 643 | let v = doc["vectors"] |
| 644 | .as_array() |
| 645 | .unwrap() |
| 646 | .iter() |
| 647 | .find(|v| v["name"] == "qk-norm-empty-sharing-one-full-chunk") |
| 648 | .unwrap(); |
| 649 | let new = unhex(v["expected"]["chunks"][0]["header_hex"].as_str().unwrap()); |
| 650 | let old = unhex(C1_QK_HEADER_HEX); |
| 651 | assert_eq!((new.len(), old.len()), (256, 256)); |
| 652 | // Re-derived by the identity change: namespace_id (16..48), chunk_key |
| 653 | // (48..80, its input includes the namespace), payload_sha256 (184..216, now |
| 654 | // a root over segment digests) and header_sha256 (224..256, covers them). |
| 655 | for range in [0..16, 80..184, 216..224] { |
| 656 | // chunk_key sits at 48..80; parent 80..112 is zero for chunk 0. |
| 657 | assert_eq!(&new[range.clone()], &old[range.clone()], "bytes {range:?}"); |
| 658 | } |
| 659 | assert_ne!(&new[16..48], &old[16..48], "namespace is re-derived"); |
| 660 | assert_ne!(&new[184..216], &old[184..216], "payload root is re-derived"); |
| 661 | |
| 662 | // The old struct still decodes and re-encodes with today's codec, and the |
| 663 | // region puts the struct unchanged at offset 0. |
| 664 | let rec = RecordHeader::decode_struct(&old).unwrap(); |
| 665 | assert_eq!(rec.encode().as_slice(), old.as_slice()); |
| 666 | let region = rec.encode_region(&seg_digests("legacy", 1)).unwrap(); |
| 667 | assert_eq!(®ion[..256], old.as_slice()); |
| 668 | assert_eq!(®ion[..256], rec.encode().as_slice()); |
| 669 | } |
| 670 | |
| 671 | /// `tests/golden/README.md` records the vectors hash that the aienos |
| 672 | /// `CONTRACT.lock` pins; changing the file without re-pinning fails here. |
| 673 | #[test] |
| 674 | fn readme_pins_the_current_vectors_hash() { |
| 675 | let text = std::fs::read(GOLDEN).unwrap(); |
| 676 | let want = hex(&Sha256::digest(&text)); |
| 677 | let readme = std::fs::read_to_string(concat!( |
| 678 | env!("CARGO_MANIFEST_DIR"), |
| 679 | "/tests/golden/README.md" |
| 680 | )) |
| 681 | .unwrap(); |
| 682 | assert!( |
| 683 | readme.contains(&format!("vectors_sha256 = `{want}`")), |
| 684 | "README.md vectors_sha256 is stale; expected {want}" |
| 685 | ); |
| 686 | } |