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/aienux/blob/main/crates/aienos-infer/tests/golden.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. 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 `aienux / crates / aienos-infer / tests / golden.rs` 688 lines ยท 23345 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 //! Golden and hostile-input tests for the GGUF reader and dequantizers. 17 //! 18 //! Real-file tests read the frozen Llama-3.2-1B-Instruct-Q4_K_M model and are 19 //! skipped with a message when it is absent, so CI without the model stays 20 //! green. Fixtures in `tests/fixtures` were produced by ggml's own 21 //! `dequantize_row_q4_K` / `dequantize_row_q6_K` (LM Studio llama.cpp 22 //! backend 2.33.0 libggml-base.so) from blocks cut out of the real file. 23 24 #![allow(clippy::chunks_exact_to_as_chunks, clippy::manual_is_multiple_of)] 25 26 use aienos_infer::quant::{dequantize, dot_q4k_f32, dot_q6k_f32, dot_row, QK_K}; 27 use aienos_infer::*; 28 use std::collections::BTreeMap; 29 30 // The model folder: $AIENOS_INFER_MODEL_DIR, default ~/models/aien-mail. 31 fn model_dir() -> std::path::PathBuf { 32 match std::env::var_os("AIENOS_INFER_MODEL_DIR") { 33 Some(d) => d.into(), 34 None => std::path::Path::new(&std::env::var_os("HOME").unwrap_or_default()) 35 .join("models/aien-mail"), 36 } 37 } 38 39 fn model_path() -> std::path::PathBuf { 40 model_dir().join("Llama-3.2-1B-Instruct-Q4_K_M.gguf") 41 } 42 43 fn meta_path() -> std::path::PathBuf { 44 model_dir().join(".cache/huggingface/download/Llama-3.2-1B-Instruct-Q4_K_M.gguf.metadata") 45 } 46 47 fn model() -> Option> { 48 let path = model_path(); 49 match std::fs::read(&path) { 50 Ok(b) => Some(b), 51 Err(e) => { 52 eprintln!("SKIP: model file {} not readable ({e})", path.display()); 53 None 54 } 55 } 56 } 57 58 fn fx(name: &str) -> Vec { 59 std::fs::read(format!( 60 "{}/tests/fixtures/{name}", 61 env!("CARGO_MANIFEST_DIR") 62 )) 63 .unwrap() 64 } 65 66 fn f32s(b: &[u8]) -> Vec { 67 b.chunks_exact(4) 68 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) 69 .collect() 70 } 71 72 // ---------------------------------------------------------------- real file 73 74 #[test] 75 fn real_header_matches_known_facts() { 76 let Some(b) = model() else { return }; 77 let g = Gguf::parse(&b).unwrap(); 78 assert_eq!(g.version, 3); 79 assert_eq!(g.alignment, 32); 80 assert_eq!(g.data_start % 32, 0); 81 assert_eq!(g.architecture().unwrap(), "llama"); 82 let p = g.llama_params().unwrap(); 83 // 16 layers, 2048 dim, 32 heads, 8 kv heads, 8192 ffn, 128256 vocab are 84 // the published Llama-3.2-1B shape (config.json); the values here are 85 // read from the file and asserted equal to those facts. 86 assert_eq!(p.block_count, 16); 87 assert_eq!(p.embedding_length, 2048); 88 assert_eq!(p.head_count, 32); 89 assert_eq!(p.head_count_kv, 8); 90 assert_eq!(p.feed_forward_length, 8192); 91 assert_eq!(p.vocab_size, 128256); 92 assert_eq!(p.context_length, 131072); 93 assert_eq!(p.rope_freq_base, 500000.0); 94 assert_eq!(p.rms_norm_eps, 1e-5); 95 let t = g.tokenizer().unwrap(); 96 assert_eq!(t.tokens.len(), 128256); 97 assert_eq!(t.token_type.unwrap().len(), 128256); 98 assert_eq!(t.merges.unwrap().len(), 280147); 99 assert!(t.scores.is_none(), "this file has no tokenizer.ggml.scores"); 100 assert_eq!(t.bos_id, Some(128000)); 101 assert_eq!(t.eos_id, Some(128009)); 102 let toks: Vec<&str> = t.tokens.strings().collect(); 103 assert_eq!(toks.len(), 128256); 104 assert_eq!(toks[128000], "<|begin_of_text|>"); 105 assert_eq!(toks[128009], "<|eot_id|>"); 106 assert_eq!(t.token_type.unwrap().i32s().count(), 128256); 107 assert_eq!(t.merges.unwrap().strings().count(), 280147); 108 } 109 110 #[test] 111 fn real_file_matches_hf_metadata_hash() { 112 let Ok(meta) = std::fs::read_to_string(meta_path()) else { 113 eprintln!("SKIP: HF metadata file absent"); 114 return; 115 }; 116 let Some(b) = model() else { return }; 117 // Line 2 of the HF cache metadata is the file's sha256 (etag). 118 let want = meta.lines().nth(1).unwrap().trim().to_string(); 119 assert_eq!(want.len(), 64); 120 let out = std::process::Command::new("sha256sum") 121 .arg(model_path()) 122 .output(); 123 let Ok(out) = out else { 124 eprintln!("SKIP: no sha256sum"); 125 return; 126 }; 127 let got = String::from_utf8_lossy(&out.stdout); 128 assert_eq!(got.split_whitespace().next().unwrap(), want); 129 assert_eq!(b.len(), 807_694_368); 130 } 131 132 #[test] 133 fn real_type_histogram_and_table_sanity() { 134 let Some(b) = model() else { return }; 135 let g = Gguf::parse(&b).unwrap(); 136 let mut h: BTreeMap = BTreeMap::new(); 137 for t in g.tensors() { 138 *h.entry(t.ty).or_default() += 1; 139 } 140 assert_eq!(h[&GgmlType::F32], 34); 141 assert_eq!(h[&GgmlType::Q4K], 96); 142 assert_eq!(h[&GgmlType::Q6K], 17); 143 assert_eq!(h.len(), 3); 144 assert_eq!(g.tensors().len(), 147); 145 // Every range inside the file; sizes match block math; and tensors are 146 // packed back to back at the alignment, which independently confirms the 147 // per-type block sizes (a wrong size would shift every following offset). 148 let mut v: Vec<&TensorInfo> = g.tensors().iter().collect(); 149 v.sort_by_key(|t| t.offset); 150 let mut expect = 0u64; 151 for t in &v { 152 assert_eq!(t.offset, expect, "{}", t.name); 153 let (bw, bb) = t.ty.block(); 154 assert_eq!(t.n_bytes, t.n_elements / bw as u64 * bb as u64); 155 assert_eq!( 156 t.row_bytes() * t.dims[1..].iter().product::(), 157 t.n_bytes 158 ); 159 assert!(g.data_start as u64 + t.offset + t.n_bytes <= b.len() as u64); 160 assert_eq!(g.tensor_data(t).len() as u64, t.n_bytes); 161 expect = (t.offset + t.n_bytes + 31) & !31; 162 } 163 assert_eq!( 164 g.data_start as u64 + v.last().map(|t| t.offset + t.n_bytes).unwrap(), 165 b.len() as u64 166 ); 167 let e = g.tensor("token_embd.weight").unwrap(); 168 assert_eq!((e.ty, e.dims[0], e.dims[1]), (GgmlType::Q6K, 2048, 128256)); 169 assert!( 170 g.tensor("output.weight").is_none(), 171 "output is tied to token_embd" 172 ); 173 } 174 175 #[test] 176 fn real_layer0_dequantizes_to_sane_values() { 177 let Some(b) = model() else { return }; 178 let g = Gguf::parse(&b).unwrap(); 179 for t in g.tensors().iter().filter(|t| t.name.starts_with("blk.0.")) { 180 let mut out = vec![0f32; t.n_elements as usize]; 181 dequantize(t.ty, g.tensor_data(t), &mut out).unwrap(); 182 assert!(out.iter().all(|v| v.is_finite()), "{}", t.name); 183 let max = out.iter().fold(0f32, |m, v| m.max(v.abs())); 184 assert!(max > 0.0 && max < 100.0, "{} max {max}", t.name); 185 } 186 } 187 188 // ---------------------------------------------------------------- ggml cross-check 189 190 #[test] 191 fn q4k_matches_ggml_bit_for_bit() { 192 let bin = fx("q4k.bin"); 193 let want = f32s(&fx("q4k.f32")); 194 let mut got = vec![0f32; want.len()]; 195 dequantize(GgmlType::Q4K, &bin, &mut got).unwrap(); 196 for (i, (a, b)) in got.iter().zip(&want).enumerate() { 197 assert_eq!(a.to_bits(), b.to_bits(), "weight {i}: {a} vs ggml {b}"); 198 } 199 } 200 201 #[test] 202 fn q6k_matches_ggml_bit_for_bit() { 203 let bin = fx("q6k.bin"); 204 let want = f32s(&fx("q6k.f32")); 205 let mut got = vec![0f32; want.len()]; 206 dequantize(GgmlType::Q6K, &bin, &mut got).unwrap(); 207 for (i, (a, b)) in got.iter().zip(&want).enumerate() { 208 assert_eq!(a.to_bits(), b.to_bits(), "weight {i}: {a} vs ggml {b}"); 209 } 210 } 211 212 #[test] 213 fn dot_helpers_match_dequant_then_dot() { 214 let bin = fx("q4k.bin"); 215 let w = f32s(&fx("q4k.f32")); 216 let x: Vec = (0..QK_K) 217 .map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.25) 218 .collect(); 219 let xa: &[f32; QK_K] = x.as_slice().try_into().unwrap(); 220 let blk: &[u8; 144] = bin[..144].try_into().unwrap(); 221 let want: f32 = w[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); 222 assert_eq!(dot_q4k_f32(blk, xa), want); 223 let bin6 = fx("q6k.bin"); 224 let w6 = f32s(&fx("q6k.f32")); 225 let blk6: &[u8; 210] = bin6[..210].try_into().unwrap(); 226 let want6: f32 = w6[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); 227 assert_eq!(dot_q6k_f32(blk6, xa), want6); 228 // Row of 4 blocks. 229 let x4: Vec = (0..4 * QK_K).map(|i| (i % 5) as f32 - 2.0).collect(); 230 let w4: f32 = w[..4 * QK_K].iter().zip(&x4).map(|(a, b)| a * b).sum(); 231 let got = dot_row(GgmlType::Q4K, &bin[..4 * 144], &x4).unwrap(); 232 assert!( 233 (got - w4).abs() <= 1e-3 * w4.abs().max(1.0), 234 "{got} vs {w4}" 235 ); 236 } 237 238 // ---------------------------------------------------------------- round trip 239 240 fn f32_to_f16(v: f32) -> u16 { 241 // Round to nearest, normal range only (test scales are well inside it). 242 let b = v.to_bits(); 243 let sign = ((b >> 16) & 0x8000) as u16; 244 let exp = ((b >> 23) & 0xff) as i32 - 127 + 15; 245 let man = b & 0x7f_ffff; 246 if v == 0.0 { 247 return sign; 248 } 249 assert!((1..31).contains(&exp), "out of f16 normal range: {v}"); 250 let mut h = ((exp as u32) << 10) | (man >> 13); 251 if man & 0x1000 != 0 { 252 h += 1; // carries into the exponent correctly 253 } 254 sign | h as u16 255 } 256 257 struct Rng(u64); 258 impl Rng { 259 fn next(&mut self) -> u64 { 260 self.0 ^= self.0 << 13; 261 self.0 ^= self.0 >> 7; 262 self.0 ^= self.0 << 17; 263 self.0 264 } 265 fn unit(&mut self) -> f32 { 266 (self.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 267 } 268 } 269 270 /// Simple reference Q4_K quantizer: 8 sub-blocks of 32, each w = d*sc*q - dmin*m. 271 fn quantize_q4k(x: &[f32; QK_K]) -> [u8; 144] { 272 let mut ds = [0f32; 8]; 273 let mut ms = [0f32; 8]; 274 for j in 0..8 { 275 let s = &x[32 * j..32 * j + 32]; 276 let mn = s.iter().cloned().fold(0f32, f32::min); 277 let mx = s.iter().cloned().fold(0f32, f32::max); 278 ms[j] = -mn; 279 ds[j] = (mx - mn) / 15.0; 280 } 281 let dmax = ds.iter().cloned().fold(0f32, f32::max); 282 let mmax = ms.iter().cloned().fold(0f32, f32::max); 283 let d16 = f32_to_f16(dmax / 63.0); 284 let m16 = f32_to_f16(mmax / 63.0); 285 let d = aienos_infer::half::f16_to_f32(d16); 286 let dmin = aienos_infer::half::f16_to_f32(m16); 287 let mut sc = [0u8; 8]; 288 let mut mn6 = [0u8; 8]; 289 for j in 0..8 { 290 sc[j] = if d > 0.0 { 291 (ds[j] / d).round().clamp(0.0, 63.0) as u8 292 } else { 293 0 294 }; 295 mn6[j] = if dmin > 0.0 { 296 (ms[j] / dmin).round().clamp(0.0, 63.0) as u8 297 } else { 298 0 299 }; 300 } 301 let mut b = [0u8; 144]; 302 b[0..2].copy_from_slice(&d16.to_le_bytes()); 303 b[2..4].copy_from_slice(&m16.to_le_bytes()); 304 // Pack 6-bit scales/mins (inverse of get_scale_min_k4). 305 for j in 0..4 { 306 b[4 + j] = sc[j] | ((sc[j + 4] >> 4) << 6); 307 b[8 + j] = mn6[j] | ((mn6[j + 4] >> 4) << 6); 308 b[12 + j] = (sc[j + 4] & 0xf) | ((mn6[j + 4] & 0xf) << 4); 309 } 310 for j in 0..8 { 311 let step = d * sc[j] as f32; 312 let off = dmin * mn6[j] as f32; 313 for l in 0..32 { 314 let q = if step > 0.0 { 315 ((x[32 * j + l] + off) / step).round().clamp(0.0, 15.0) as u8 316 } else { 317 0 318 }; 319 // sub-blocks 2k (low nibble) and 2k+1 (high nibble) share 32 bytes. 320 let byte = &mut b[16 + 32 * (j / 2) + l]; 321 if j % 2 == 0 { 322 *byte |= q 323 } else { 324 *byte |= q << 4 325 } 326 } 327 } 328 b 329 } 330 331 /// Simple reference Q6_K quantizer: 16 sub-blocks of 16, w = d*sc*(q-32). 332 fn quantize_q6k(x: &[f32; QK_K]) -> [u8; 210] { 333 let mut sub = [0f32; 16]; 334 for j in 0..16 { 335 sub[j] = x[16 * j..16 * j + 16] 336 .iter() 337 .fold(0f32, |m, v| m.max(v.abs())) 338 / 32.0; 339 } 340 let smax = sub.iter().cloned().fold(0f32, f32::max); 341 let d16 = f32_to_f16(smax / 127.0); 342 let d = aienos_infer::half::f16_to_f32(d16); 343 let mut b = [0u8; 210]; 344 b[208..210].copy_from_slice(&d16.to_le_bytes()); 345 let mut sc = [0i8; 16]; 346 for j in 0..16 { 347 sc[j] = if d > 0.0 { 348 (sub[j] / d).round().clamp(0.0, 127.0) as i8 349 } else { 350 0 351 }; 352 b[192 + j] = sc[j] as u8; 353 } 354 let q = |p: usize| -> u8 { 355 let s = d * sc[p / 16] as f32; 356 if s > 0.0 { 357 ((x[p] / s).round() + 32.0).clamp(0.0, 63.0) as u8 358 } else { 359 32 360 } 361 }; 362 for h in 0..2 { 363 for l in 0..32 { 364 let base = 128 * h; 365 let (q1, q2, q3, q4) = ( 366 q(base + l), 367 q(base + l + 32), 368 q(base + l + 64), 369 q(base + l + 96), 370 ); 371 b[64 * h + l] = (q1 & 0xf) | ((q3 & 0xf) << 4); 372 b[64 * h + l + 32] = (q2 & 0xf) | ((q4 & 0xf) << 4); 373 b[128 + 32 * h + l] = 374 (q1 >> 4) | ((q2 >> 4) << 2) | ((q3 >> 4) << 4) | ((q4 >> 4) << 6); 375 } 376 } 377 b 378 } 379 380 fn max_round_trip_err(ty: GgmlType, trials: usize) -> f32 { 381 let mut rng = Rng(0x9e37_79b9_7f4a_7c15); 382 let mut worst = 0f32; 383 for _ in 0..trials { 384 let mut x = [0f32; QK_K]; 385 for v in x.iter_mut() { 386 *v = rng.unit(); 387 } 388 let mut y = [0f32; QK_K]; 389 match ty { 390 GgmlType::Q4K => dequantize(ty, &quantize_q4k(&x), &mut y).unwrap(), 391 _ => dequantize(ty, &quantize_q6k(&x), &mut y).unwrap(), 392 } 393 for (a, b) in x.iter().zip(&y) { 394 worst = worst.max((a - b).abs()); 395 } 396 } 397 worst 398 } 399 400 #[test] 401 fn q4k_round_trip_error_bound() { 402 // x in [-1,1]: a 4-bit step over a sub-block range <= 2 is 2/15 = 0.133, 403 // so half-step 0.067 plus 6-bit scale/min rounding stays under 0.1. 404 let worst = max_round_trip_err(GgmlType::Q4K, 200); 405 eprintln!("q4k round trip max abs error {worst}"); 406 assert!(worst < 0.1, "{worst}"); 407 } 408 409 #[test] 410 fn q6k_round_trip_error_bound() { 411 // 6-bit: step = maxabs/32 <= 1/32. The grid is -32..31, so +maxabs clamps 412 // to 31 (one full step, 0.031) plus half-step rounding 0.016 -> under 0.05. 413 let worst = max_round_trip_err(GgmlType::Q6K, 200); 414 eprintln!("q6k round trip max abs error {worst}"); 415 assert!(worst < 0.05, "{worst}"); 416 } 417 418 #[test] 419 fn round_trip_exact_when_grid_aligned() { 420 // Values that lie exactly on the Q4_K grid must come back exactly: 421 // d = dmin = 1/64 scales are exact in f16. 422 let mut x = [0f32; QK_K]; 423 for (i, v) in x.iter_mut().enumerate() { 424 *v = (i % 16) as f32; // each sub-block spans 0..15: sc=1*d, m=0 425 } 426 // d = 15/15 = 1 -> scale 63 needs d=1/63 which is inexact; use the 427 // hand-built path instead: d=1, sc=1, min=0. 428 let mut b = [0u8; 144]; 429 b[0..2].copy_from_slice(&0x3c00u16.to_le_bytes()); 430 for j in 0..4 { 431 b[4 + j] = 1; 432 } 433 for j in 0..4 { 434 b[12 + j] = 1; 435 } 436 for l in 0..128 { 437 let lo = (l % 16) as u8; 438 b[16 + l] = lo | (lo << 4); 439 } 440 let mut y = [0f32; QK_K]; 441 dequantize(GgmlType::Q4K, &b, &mut y).unwrap(); 442 assert_eq!(x.to_vec(), y.to_vec()); 443 } 444 445 // ---------------------------------------------------------------- hostile input 446 447 /// Minimal valid GGUF builder for hostile-input tests. 448 struct B(Vec); 449 impl B { 450 fn new(n_tensors: u64, n_kv: u64) -> Self { 451 let mut v = b"GGUF".to_vec(); 452 v.extend(3u32.to_le_bytes()); 453 v.extend(n_tensors.to_le_bytes()); 454 v.extend(n_kv.to_le_bytes()); 455 B(v) 456 } 457 fn s(&mut self, s: &str) { 458 self.0.extend((s.len() as u64).to_le_bytes()); 459 self.0.extend(s.as_bytes()); 460 } 461 fn kv_u32(&mut self, k: &str, v: u32) { 462 self.s(k); 463 self.0.extend(4u32.to_le_bytes()); 464 self.0.extend(v.to_le_bytes()); 465 } 466 fn tensor(&mut self, name: &str, dims: &[u64], ty: u32, off: u64) { 467 self.s(name); 468 self.0.extend((dims.len() as u32).to_le_bytes()); 469 for d in dims { 470 self.0.extend(d.to_le_bytes()); 471 } 472 self.0.extend(ty.to_le_bytes()); 473 self.0.extend(off.to_le_bytes()); 474 } 475 fn pad_data(mut self, n: usize) -> Vec { 476 while self.0.len() % 32 != 0 { 477 self.0.push(0); 478 } 479 self.0.extend(std::iter::repeat_n(0u8, n)); 480 self.0 481 } 482 } 483 484 fn good_small() -> Vec { 485 let mut b = B::new(1, 2); 486 b.kv_u32("a.b", 7); 487 b.s("tokens"); 488 b.0.extend(9u32.to_le_bytes()); // array 489 b.0.extend(8u32.to_le_bytes()); // of string 490 b.0.extend(2u64.to_le_bytes()); 491 b.s("hi"); 492 b.s("yo"); 493 b.tensor("w", &[256], 12, 0); 494 b.pad_data(144) 495 } 496 497 #[test] 498 fn small_good_file_parses() { 499 let f = good_small(); 500 let g = Gguf::parse(&f).unwrap(); 501 assert_eq!(g.u32_key("a.b").unwrap(), 7); 502 let toks: Vec<_> = g.array_key("tokens").unwrap().strings().collect(); 503 assert_eq!(toks, ["hi", "yo"]); 504 assert_eq!(g.tensor("w").unwrap().n_bytes, 144); 505 assert_eq!(g.u32_key("nope"), Err(GgufError::Missing("nope"))); 506 assert_eq!(g.str_key("a.b"), Err(GgufError::WrongType("a.b"))); 507 } 508 509 #[test] 510 fn every_truncation_is_an_error_not_a_panic() { 511 let f = good_small(); 512 for n in 0..f.len() { 513 assert!(Gguf::parse(&f[..n]).is_err(), "len {n} should fail"); 514 } 515 // Real file: all short lengths plus a strided sweep through the header. 516 if let Some(b) = model() { 517 let g = Gguf::parse(&b).unwrap(); 518 for n in 0..3000 { 519 assert!(Gguf::parse(&b[..n]).is_err(), "len {n}"); 520 } 521 let mut n = 3000; 522 while n < g.data_start { 523 assert!(Gguf::parse(&b[..n]).is_err(), "len {n}"); 524 n += 99_991; 525 } 526 // Cutting inside the tensor data must fail the range check. 527 assert_eq!( 528 Gguf::parse(&b[..b.len() - 1]).unwrap_err(), 529 GgufError::TensorOutOfRange 530 ); 531 assert!(Gguf::parse(&b[..g.data_start]).is_err()); 532 } 533 } 534 535 #[test] 536 fn absurd_counts_and_bad_fields() { 537 let mut f = B::new(u64::MAX, 0).0; 538 assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); 539 f = B::new(0, u64::MAX / 2).0; 540 assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); 541 f = B::new(1_000_000, 0).pad_data(64); 542 assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); 543 let mut bad_magic = good_small(); 544 bad_magic[0] = b'X'; 545 assert_eq!(Gguf::parse(&bad_magic).unwrap_err(), GgufError::BadMagic); 546 let mut bad_ver = good_small(); 547 bad_ver[4] = 2; 548 assert_eq!( 549 Gguf::parse(&bad_ver).unwrap_err(), 550 GgufError::UnsupportedVersion(2) 551 ); 552 553 // Offset past end. 554 let mut b = B::new(1, 0); 555 b.tensor("w", &[256], 12, 1 << 40); 556 assert_eq!( 557 Gguf::parse(&b.pad_data(144)).unwrap_err(), 558 GgufError::TensorOutOfRange 559 ); 560 // Offset + size overflow u64. 561 let mut b = B::new(1, 0); 562 b.tensor("w", &[256], 12, u64::MAX - 8); 563 assert_eq!( 564 Gguf::parse(&b.pad_data(144)).unwrap_err(), 565 GgufError::Overflow 566 ); 567 // Misaligned offset. 568 let mut b = B::new(1, 0); 569 b.tensor("w", &[256], 12, 16); 570 assert_eq!( 571 Gguf::parse(&b.pad_data(400)).unwrap_err(), 572 GgufError::TensorOutOfRange 573 ); 574 // Dimension product overflow. 575 let mut b = B::new(1, 0); 576 b.tensor("w", &[1 << 40, 1 << 40], 0, 0); 577 assert_eq!( 578 Gguf::parse(&b.pad_data(8)).unwrap_err(), 579 GgufError::Overflow 580 ); 581 // Row not a whole number of blocks. 582 let mut b = B::new(1, 0); 583 b.tensor("w", &[255], 12, 0); 584 assert_eq!( 585 Gguf::parse(&b.pad_data(400)).unwrap_err(), 586 GgufError::BadDims 587 ); 588 // 0 and 5 dims. 589 let mut b = B::new(1, 0); 590 b.tensor("w", &[], 0, 0); 591 assert_eq!(Gguf::parse(&b.pad_data(8)).unwrap_err(), GgufError::BadDims); 592 let mut b = B::new(1, 0); 593 b.tensor("w", &[1, 1, 1, 1, 1], 0, 0); 594 assert_eq!(Gguf::parse(&b.pad_data(8)).unwrap_err(), GgufError::BadDims); 595 // Unknown tensor type, unknown kv type. 596 let mut b = B::new(1, 0); 597 b.tensor("w", &[32], 99, 0); 598 assert_eq!( 599 Gguf::parse(&b.pad_data(8)).unwrap_err(), 600 GgufError::UnsupportedType(99) 601 ); 602 let mut b = B::new(0, 1); 603 b.s("k"); 604 b.0.extend(77u32.to_le_bytes()); 605 assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::BadValueType(77)); 606 // Zero and non power of two alignment. 607 for a in [0u32, 3] { 608 let mut b = B::new(0, 1); 609 b.kv_u32("general.alignment", a); 610 assert_eq!( 611 Gguf::parse(&b.pad_data(8)).unwrap_err(), 612 GgufError::BadAlignment 613 ); 614 } 615 // Huge string length, huge array length, nested array. 616 let mut b = B::new(0, 1); 617 b.0.extend(u64::MAX.to_le_bytes()); 618 assert!(Gguf::parse(&b.0).is_err()); 619 let mut b = B::new(0, 1); 620 b.s("k"); 621 b.0.extend(9u32.to_le_bytes()); 622 b.0.extend(4u32.to_le_bytes()); 623 b.0.extend(u64::MAX.to_le_bytes()); 624 assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::Overflow); 625 let mut b = B::new(0, 1); 626 b.s("k"); 627 b.0.extend(9u32.to_le_bytes()); 628 b.0.extend(8u32.to_le_bytes()); 629 b.0.extend((1u64 << 60).to_le_bytes()); 630 assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::TooMany); 631 let mut b = B::new(0, 1); 632 b.s("k"); 633 b.0.extend(9u32.to_le_bytes()); 634 b.0.extend(9u32.to_le_bytes()); 635 b.0.extend(1u64.to_le_bytes()); 636 assert!(Gguf::parse(&b.0).is_err()); 637 // Invalid UTF-8 key. 638 let mut b = B::new(0, 1); 639 b.0.extend(2u64.to_le_bytes()); 640 b.0.extend([0xff, 0xfe]); 641 b.0.extend(4u32.to_le_bytes()); 642 b.0.extend(0u32.to_le_bytes()); 643 assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::BadUtf8); 644 } 645 646 #[test] 647 fn byte_flip_fuzz_never_panics() { 648 let f = good_small(); 649 let mut rng = Rng(0x1234_5678_9abc_def1); 650 for _ in 0..20_000 { 651 let mut g = f.clone(); 652 for _ in 0..1 + rng.next() % 3 { 653 let i = (rng.next() % g.len() as u64) as usize; 654 g[i] = rng.next() as u8; 655 } 656 if rng.next() % 4 == 0 { 657 let n = (rng.next() % g.len() as u64) as usize; 658 g.truncate(n); 659 } 660 if let Ok(p) = Gguf::parse(&g) { 661 // Accessors on whatever parsed must also be panic free. 662 for t in p.tensors() { 663 let _ = p.tensor_data(t); 664 } 665 for (_, v) in p.kvs() { 666 if let Value::Array(a) = v { 667 let _ = a.strings().count() 668 + a.u32s().count() 669 + a.i32s().count() 670 + a.f32s().count(); 671 } 672 } 673 let _ = p.llama_params(); 674 let _ = p.tokenizer(); 675 } 676 } 677 } 678 679 #[test] 680 fn dequantize_rejects_bad_lengths_without_panic() { 681 let mut out = vec![0f32; 256]; 682 for n in [0usize, 1, 143, 145, 288] { 683 assert!(dequantize(GgmlType::Q4K, &vec![0u8; n], &mut out).is_err()); 684 } 685 assert!(dequantize(GgmlType::Q6K, &[0u8; 209], &mut out).is_err()); 686 let mut odd = vec![0f32; 100]; 687 assert!(dequantize(GgmlType::Q4K, &[0u8; 144], &mut odd).is_err()); 688 }