diff --git a/Cargo.lock b/Cargo.lock index ad81e10d..4fc4a0cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -108,6 +108,10 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aienos-infer" +version = "0.1.0" + [[package]] name = "aienos-kernel" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 460b5419..a014812d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ members = [ "crates/aienos-evidence", "crates/aienos-store-tool", "crates/aienos-explain", + "crates/aienos-infer", ] [workspace.package] diff --git a/crates/aienos-infer/Cargo.toml b/crates/aienos-infer/Cargo.toml new file mode 100644 index 00000000..c4cf7150 --- /dev/null +++ b/crates/aienos-infer/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "aienos-infer" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "no_std GGUF reader and ggml block dequantizers for native AIENOS inference" + +[lib] +path = "src/lib.rs" diff --git a/crates/aienos-infer/src/gguf.rs b/crates/aienos-infer/src/gguf.rs new file mode 100644 index 00000000..263d6267 --- /dev/null +++ b/crates/aienos-infer/src/gguf.rs @@ -0,0 +1,639 @@ +//! Bounded GGUF v3 reader over a byte slice. +//! +//! Layout (GGUF spec, little endian): magic `GGUF`, u32 version, u64 tensor +//! count, u64 key/value count, the key/value pairs, the tensor infos, padding +//! to `general.alignment` (default 32), then the tensor data. + +use alloc::vec::Vec; +use core::fmt; + +use crate::half::{bf16_to_f32, f16_to_f32}; + +/// Everything that can go wrong while reading a GGUF file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GgufError { + /// A read ran past the end of the input at this byte offset. + Truncated(usize), + BadMagic, + UnsupportedVersion(u32), + /// A declared count cannot fit in the remaining bytes. + TooMany, + BadUtf8, + /// Unknown or unsupported key/value type code. + BadValueType(u32), + /// `general.alignment` is zero, not a power of two, or not a u32. + BadAlignment, + /// Arithmetic overflow while computing sizes or offsets. + Overflow, + /// Tensor type code this reader cannot size. + UnsupportedType(u32), + /// More than 4 dimensions or zero dimensions. + BadDims, + /// Tensor offset or byte range falls outside the data section, or its + /// offset is not a multiple of the alignment. + TensorOutOfRange, + /// Required key absent. + Missing(&'static str), + /// Key present with a different type than requested. + WrongType(&'static str), +} + +impl fmt::Display for GgufError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self:?}") + } +} + +/// GGUF metadata value type codes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ValueType { + U8, + I8, + U16, + I16, + U32, + I32, + F32, + Bool, + Str, + Array, + U64, + I64, + F64, +} + +impl ValueType { + fn from_code(c: u32) -> Result { + Ok(match c { + 0 => Self::U8, + 1 => Self::I8, + 2 => Self::U16, + 3 => Self::I16, + 4 => Self::U32, + 5 => Self::I32, + 6 => Self::F32, + 7 => Self::Bool, + 8 => Self::Str, + 9 => Self::Array, + 10 => Self::U64, + 11 => Self::I64, + 12 => Self::F64, + other => return Err(GgufError::BadValueType(other)), + }) + } + + /// Byte size for fixed-size scalars, `None` for string/array. + fn fixed_size(self) -> Option { + match self { + Self::U8 | Self::I8 | Self::Bool => Some(1), + Self::U16 | Self::I16 => Some(2), + Self::U32 | Self::I32 | Self::F32 => Some(4), + Self::U64 | Self::I64 | Self::F64 => Some(8), + Self::Str | Self::Array => None, + } + } +} + +/// A one-dimensional array of scalars or strings, validated at parse time. +#[derive(Debug, Clone, Copy)] +pub struct ArrayView<'a> { + pub elem: ValueType, + len: usize, + data: &'a [u8], +} + +impl<'a> ArrayView<'a> { + /// Number of elements. + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + /// Iterate strings; empty unless the element type is string. + pub fn strings(&self) -> impl Iterator + 'a { + let mut cur = Cursor::new(self.data); + let n = if self.elem == ValueType::Str { + self.len + } else { + 0 + }; + (0..n).map_while(move |_| cur.str().ok()) + } + fn chunks(&self, want: &[ValueType], size: usize) -> impl Iterator + 'a { + let ok = want.contains(&self.elem); + let data = if ok { self.data } else { &[][..] }; + data.chunks_exact(size) + } + /// Iterate u32 elements (empty unless element type is u32). + pub fn u32s(&self) -> impl Iterator + 'a { + self.chunks(&[ValueType::U32], 4) + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) + } + /// Iterate i32 elements (empty unless element type is i32). + pub fn i32s(&self) -> impl Iterator + 'a { + self.chunks(&[ValueType::I32], 4) + .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])) + } + /// Iterate f32 elements (empty unless element type is f32). + pub fn f32s(&self) -> impl Iterator + 'a { + self.chunks(&[ValueType::F32], 4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + } +} + +/// A metadata value. +#[derive(Debug, Clone, Copy)] +pub enum Value<'a> { + U8(u8), + I8(i8), + U16(u16), + I16(i16), + U32(u32), + I32(i32), + F32(f32), + Bool(bool), + Str(&'a str), + Array(ArrayView<'a>), + U64(u64), + I64(i64), + F64(f64), +} + +impl<'a> Value<'a> { + /// Any integer value that fits in u64 (non-negative). + pub fn as_u64(&self) -> Option { + match *self { + Value::U8(v) => Some(v as u64), + Value::U16(v) => Some(v as u64), + Value::U32(v) => Some(v as u64), + Value::U64(v) => Some(v), + Value::I8(v) => u64::try_from(v).ok(), + Value::I16(v) => u64::try_from(v).ok(), + Value::I32(v) => u64::try_from(v).ok(), + Value::I64(v) => u64::try_from(v).ok(), + _ => None, + } + } + pub fn as_f32(&self) -> Option { + match *self { + Value::F32(v) => Some(v), + Value::F64(v) => Some(v as f32), + _ => None, + } + } + pub fn as_str(&self) -> Option<&'a str> { + match *self { + Value::Str(s) => Some(s), + _ => None, + } + } + pub fn as_array(&self) -> Option> { + match *self { + Value::Array(a) => Some(a), + _ => None, + } + } +} + +/// ggml tensor storage types. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum GgmlType { + F32, + F16, + Q4_0, + Q4_1, + Q5_0, + Q5_1, + Q8_0, + Q8_1, + Q2K, + Q3K, + Q4K, + Q5K, + Q6K, + Q8K, + I8, + I16, + I32, + I64, + F64, + BF16, +} + +impl GgmlType { + pub fn from_code(c: u32) -> Result { + Ok(match c { + 0 => Self::F32, + 1 => Self::F16, + 2 => Self::Q4_0, + 3 => Self::Q4_1, + 6 => Self::Q5_0, + 7 => Self::Q5_1, + 8 => Self::Q8_0, + 9 => Self::Q8_1, + 10 => Self::Q2K, + 11 => Self::Q3K, + 12 => Self::Q4K, + 13 => Self::Q5K, + 14 => Self::Q6K, + 15 => Self::Q8K, + 24 => Self::I8, + 25 => Self::I16, + 26 => Self::I32, + 27 => Self::I64, + 28 => Self::F64, + 30 => Self::BF16, + other => return Err(GgufError::UnsupportedType(other)), + }) + } + + /// (weights per block, bytes per block). + pub fn block(self) -> (usize, usize) { + match self { + Self::F32 | Self::I32 => (1, 4), + Self::F16 | Self::BF16 | Self::I16 => (1, 2), + Self::I8 => (1, 1), + Self::I64 | Self::F64 => (1, 8), + Self::Q4_0 => (32, 18), + Self::Q4_1 => (32, 20), + Self::Q5_0 => (32, 22), + Self::Q5_1 => (32, 24), + Self::Q8_0 => (32, 34), + Self::Q8_1 => (32, 36), + Self::Q2K => (256, 84), + Self::Q3K => (256, 110), + Self::Q4K => (256, 144), + Self::Q5K => (256, 176), + Self::Q6K => (256, 210), + Self::Q8K => (256, 292), + } + } +} + +/// One entry of the tensor table. +#[derive(Debug, Clone)] +pub struct TensorInfo<'a> { + pub name: &'a str, + /// Dimensions, `dims[0]` is the contiguous (row) length. Only the first + /// `n_dims` are meaningful. + pub dims: [u64; 4], + pub n_dims: u32, + pub ty: GgmlType, + /// Offset from the start of the data section. + pub offset: u64, + /// Total weights. + pub n_elements: u64, + /// Total bytes, from the type's block math. + pub n_bytes: u64, +} + +impl TensorInfo<'_> { + /// Bytes in one row (`dims[0]` weights). + pub fn row_bytes(&self) -> u64 { + let (bw, bb) = self.ty.block(); + self.dims[0] / bw as u64 * bb as u64 + } +} + +/// Bounds-checked little-endian reader. +struct Cursor<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn new(b: &'a [u8]) -> Self { + Self { b, pos: 0 } + } + fn remaining(&self) -> usize { + self.b.len() - self.pos + } + fn take(&mut self, n: usize) -> Result<&'a [u8], GgufError> { + if n > self.remaining() { + return Err(GgufError::Truncated(self.pos)); + } + let s = &self.b[self.pos..self.pos + n]; + self.pos += n; + Ok(s) + } + fn arr(&mut self) -> Result<[u8; N], GgufError> { + let s = self.take(N)?; + let mut a = [0u8; N]; + a.copy_from_slice(s); + Ok(a) + } + fn u8(&mut self) -> Result { + Ok(self.arr::<1>()?[0]) + } + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.arr()?)) + } + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.arr()?)) + } + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.arr()?)) + } + fn len64(&mut self) -> Result { + usize::try_from(self.u64()?).map_err(|_| GgufError::Overflow) + } + fn str(&mut self) -> Result<&'a str, GgufError> { + let n = self.len64()?; + let s = self.take(n)?; + core::str::from_utf8(s).map_err(|_| GgufError::BadUtf8) + } + + fn value(&mut self, ty: ValueType) -> Result, GgufError> { + Ok(match ty { + ValueType::U8 => Value::U8(self.u8()?), + ValueType::I8 => Value::I8(self.u8()? as i8), + ValueType::U16 => Value::U16(self.u16()?), + ValueType::I16 => Value::I16(self.u16()? as i16), + ValueType::U32 => Value::U32(self.u32()?), + ValueType::I32 => Value::I32(self.u32()? as i32), + ValueType::F32 => Value::F32(f32::from_bits(self.u32()?)), + ValueType::Bool => match self.u8()? { + 0 => Value::Bool(false), + 1 => Value::Bool(true), + other => return Err(GgufError::BadValueType(other as u32)), + }, + ValueType::Str => Value::Str(self.str()?), + ValueType::U64 => Value::U64(self.u64()?), + ValueType::I64 => Value::I64(self.u64()? as i64), + ValueType::F64 => Value::F64(f64::from_bits(self.u64()?)), + ValueType::Array => { + let elem = ValueType::from_code(self.u32()?)?; + let len = self.len64()?; + let start = self.pos; + match elem.fixed_size() { + Some(sz) => { + let total = len.checked_mul(sz).ok_or(GgufError::Overflow)?; + self.take(total)?; + } + None if elem == ValueType::Str => { + // Each string needs at least its 8-byte length. + if len > self.remaining() / 8 { + return Err(GgufError::TooMany); + } + for _ in 0..len { + self.str()?; + } + } + None => return Err(GgufError::BadValueType(9)), // nested arrays + } + Value::Array(ArrayView { + elem, + len, + data: &self.b[start..self.pos], + }) + } + }) + } +} + +/// A parsed GGUF file borrowing the input bytes. +#[derive(Debug)] +pub struct Gguf<'a> { + bytes: &'a [u8], + pub version: u32, + kv: Vec<(&'a str, Value<'a>)>, + tensors: Vec>, + pub alignment: u64, + /// Byte offset of the tensor data section within the input. + pub data_start: usize, +} + +impl<'a> Gguf<'a> { + /// Parse and fully validate the header, metadata and tensor table. + pub fn parse(bytes: &'a [u8]) -> Result { + let mut c = Cursor::new(bytes); + if c.take(4)? != b"GGUF" { + return Err(GgufError::BadMagic); + } + let version = c.u32()?; + if version != 3 { + return Err(GgufError::UnsupportedVersion(version)); + } + let n_tensors = c.len64()?; + let n_kv = c.len64()?; + // A kv needs >= 8 (key len) + 4 (type) bytes; a tensor info >= 8+4+8+4+8. + if n_kv > c.remaining() / 12 || n_tensors > c.remaining() / 32 { + return Err(GgufError::TooMany); + } + + let mut kv = Vec::with_capacity(n_kv); + for _ in 0..n_kv { + let key = c.str()?; + let ty = ValueType::from_code(c.u32()?)?; + kv.push((key, c.value(ty)?)); + } + + let alignment = match kv.iter().find(|(k, _)| *k == "general.alignment") { + None => 32, + Some((_, v)) => match *v { + Value::U32(a) if a != 0 && a.is_power_of_two() => a as u64, + _ => return Err(GgufError::BadAlignment), + }, + }; + + let mut tensors: Vec> = Vec::with_capacity(n_tensors); + for _ in 0..n_tensors { + let name = c.str()?; + let n_dims = c.u32()?; + if n_dims == 0 || n_dims > 4 { + return Err(GgufError::BadDims); + } + let mut dims = [1u64; 4]; + for d in dims.iter_mut().take(n_dims as usize) { + *d = c.u64()?; + } + let ty = GgmlType::from_code(c.u32()?)?; + let offset = c.u64()?; + let mut n_elements: u64 = 1; + for d in dims { + n_elements = n_elements.checked_mul(d).ok_or(GgufError::Overflow)?; + } + let (bw, bb) = ty.block(); + if dims[0] % bw as u64 != 0 { + return Err(GgufError::BadDims); + } + let n_bytes = (n_elements / bw as u64) + .checked_mul(bb as u64) + .ok_or(GgufError::Overflow)?; + tensors.push(TensorInfo { + name, + dims, + n_dims, + ty, + offset, + n_elements, + n_bytes, + }); + } + + let pos = c.pos as u64; + let data_start = + pos.checked_add(alignment - 1).ok_or(GgufError::Overflow)? & !(alignment - 1); + let data_start = usize::try_from(data_start).map_err(|_| GgufError::Overflow)?; + if data_start > bytes.len() { + return Err(GgufError::Truncated(bytes.len())); + } + let data_len = (bytes.len() - data_start) as u64; + for t in &tensors { + let end = t.offset.checked_add(t.n_bytes).ok_or(GgufError::Overflow)?; + if end > data_len || t.offset % alignment != 0 { + return Err(GgufError::TensorOutOfRange); + } + } + + Ok(Self { + bytes, + version, + kv, + tensors, + alignment, + data_start, + }) + } + + /// All key/value pairs in file order. + pub fn kvs(&self) -> &[(&'a str, Value<'a>)] { + &self.kv + } + /// Look up a metadata value. + pub fn get(&self, key: &str) -> Option> { + self.kv.iter().find(|(k, _)| *k == key).map(|(_, v)| *v) + } + /// All tensor infos in file order. + pub fn tensors(&self) -> &[TensorInfo<'a>] { + &self.tensors + } + /// Find a tensor by name. + pub fn tensor(&self, name: &str) -> Option<&TensorInfo<'a>> { + self.tensors.iter().find(|t| t.name == name) + } + /// Raw bytes of a tensor (range validated at parse time). + pub fn tensor_data(&self, t: &TensorInfo<'_>) -> &'a [u8] { + let s = self.data_start + t.offset as usize; + &self.bytes[s..s + t.n_bytes as usize] + } + + fn req(&self, key: &'static str) -> Result, GgufError> { + self.get(key).ok_or(GgufError::Missing(key)) + } + /// Required unsigned integer key. + pub fn u64_key(&self, key: &'static str) -> Result { + self.req(key)?.as_u64().ok_or(GgufError::WrongType(key)) + } + /// Required key that must fit in u32. + pub fn u32_key(&self, key: &'static str) -> Result { + u32::try_from(self.u64_key(key)?).map_err(|_| GgufError::WrongType(key)) + } + pub fn f32_key(&self, key: &'static str) -> Result { + self.req(key)?.as_f32().ok_or(GgufError::WrongType(key)) + } + pub fn str_key(&self, key: &'static str) -> Result<&'a str, GgufError> { + self.req(key)?.as_str().ok_or(GgufError::WrongType(key)) + } + pub fn array_key(&self, key: &'static str) -> Result, GgufError> { + self.req(key)?.as_array().ok_or(GgufError::WrongType(key)) + } + + /// `general.architecture` (for Llama-3.2 this is `llama`). + pub fn architecture(&self) -> Result<&'a str, GgufError> { + self.str_key("general.architecture") + } + + /// Hyperparameters, read from `.` keys as written by llama.cpp. + pub fn llama_params(&self) -> Result { + if self.architecture()? != "llama" { + return Err(GgufError::WrongType("general.architecture")); + } + let vocab_size = match self.get("llama.vocab_size") { + Some(v) => v + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .ok_or(GgufError::WrongType("llama.vocab_size"))?, + // Not stored by llama.cpp converters; derive from the token list. + None => u32::try_from(self.array_key("tokenizer.ggml.tokens")?.len()) + .map_err(|_| GgufError::Overflow)?, + }; + Ok(LlamaParams { + block_count: self.u32_key("llama.block_count")?, + embedding_length: self.u32_key("llama.embedding_length")?, + head_count: self.u32_key("llama.attention.head_count")?, + head_count_kv: self.u32_key("llama.attention.head_count_kv")?, + feed_forward_length: self.u32_key("llama.feed_forward_length")?, + context_length: self.u32_key("llama.context_length")?, + rope_freq_base: self.f32_key("llama.rope.freq_base")?, + rms_norm_eps: self.f32_key("llama.attention.layer_norm_rms_epsilon")?, + vocab_size, + }) + } + + /// Token strings, scores and types plus special ids. + pub fn tokenizer(&self) -> Result, GgufError> { + let tokens = self.array_key("tokenizer.ggml.tokens")?; + let scores = self.array_key("tokenizer.ggml.scores").ok(); + let token_type = self.array_key("tokenizer.ggml.token_type").ok(); + let merges = self.array_key("tokenizer.ggml.merges").ok(); + Ok(TokenizerData { + tokens, + scores, + token_type, + merges, + bos_id: self.u32_key("tokenizer.ggml.bos_token_id").ok(), + eos_id: self.u32_key("tokenizer.ggml.eos_token_id").ok(), + }) + } +} + +/// Model hyperparameters needed by the Llama graph. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct LlamaParams { + pub block_count: u32, + pub embedding_length: u32, + pub head_count: u32, + pub head_count_kv: u32, + pub feed_forward_length: u32, + pub context_length: u32, + pub rope_freq_base: f32, + pub rms_norm_eps: f32, + pub vocab_size: u32, +} + +/// Tokenizer arrays as stored in the file. +#[derive(Debug, Clone, Copy)] +pub struct TokenizerData<'a> { + pub tokens: ArrayView<'a>, + pub scores: Option>, + pub token_type: Option>, + pub merges: Option>, + pub bos_id: Option, + pub eos_id: Option, +} + +/// Dequantize any row-contiguous slice of a tensor of the plain float types +/// into `out`; quantized types go through [`crate::quant::dequantize`]. +pub(crate) fn plain_to_f32(ty: GgmlType, src: &[u8], out: &mut [f32]) -> bool { + match ty { + GgmlType::F32 => { + for (o, c) in out.iter_mut().zip(src.chunks_exact(4)) { + *o = f32::from_le_bytes([c[0], c[1], c[2], c[3]]); + } + } + GgmlType::F16 => { + for (o, c) in out.iter_mut().zip(src.chunks_exact(2)) { + *o = f16_to_f32(u16::from_le_bytes([c[0], c[1]])); + } + } + GgmlType::BF16 => { + for (o, c) in out.iter_mut().zip(src.chunks_exact(2)) { + *o = bf16_to_f32(u16::from_le_bytes([c[0], c[1]])); + } + } + _ => return false, + } + true +} diff --git a/crates/aienos-infer/src/half.rs b/crates/aienos-infer/src/half.rs new file mode 100644 index 00000000..86925a39 --- /dev/null +++ b/crates/aienos-infer/src/half.rs @@ -0,0 +1,52 @@ +//! IEEE binary16 and bfloat16 to f32 without std. + +/// Convert an IEEE 754 binary16 bit pattern to f32 (exact for all inputs, +/// including subnormals, infinities and NaNs). +pub fn f16_to_f32(h: u16) -> f32 { + let sign = ((h >> 15) as u32) << 31; + let exp = ((h >> 10) & 0x1f) as u32; + let man = (h & 0x3ff) as u32; + let bits = if exp == 0 { + if man == 0 { + sign + } else { + // Subnormal: normalise. + let shift = man.leading_zeros() - 21; // man has <= 10 bits + let m = (man << shift) & 0x3ff; + let e = 113 - shift; // 127 - 15 + 1 - shift + sign | (e << 23) | (m << 13) + } + } else if exp == 0x1f { + sign | 0x7f80_0000 | (man << 13) + } else { + sign | ((exp + 112) << 23) | (man << 13) + }; + f32::from_bits(bits) +} + +/// Convert a bfloat16 bit pattern to f32. +pub fn bf16_to_f32(b: u16) -> f32 { + f32::from_bits((b as u32) << 16) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_values() { + assert_eq!(f16_to_f32(0x0000), 0.0); + assert_eq!(f16_to_f32(0x3c00), 1.0); + assert_eq!(f16_to_f32(0xc000), -2.0); + assert_eq!(f16_to_f32(0x3800), 0.5); + assert_eq!(f16_to_f32(0x7bff), 65504.0); + assert_eq!(f16_to_f32(0x0400), f32::from_bits(0x3880_0000)); // 2^-14 smallest normal + assert_eq!(f16_to_f32(0x0001), f32::from_bits(0x3380_0000)); // 2^-24 smallest subnormal + assert_eq!(f16_to_f32(0x03ff), 1023.0 / 16_777_216.0); // 1023 * 2^-24 + assert!(f16_to_f32(0x7c00).is_infinite()); + assert!(f16_to_f32(0xfc00).is_sign_negative()); + assert!(f16_to_f32(0x7e00).is_nan()); + assert_eq!(f16_to_f32(0x8000).to_bits(), 0x8000_0000); + assert_eq!(bf16_to_f32(0x3f80), 1.0); + } +} diff --git a/crates/aienos-infer/src/lib.rs b/crates/aienos-infer/src/lib.rs new file mode 100644 index 00000000..be51d20c --- /dev/null +++ b/crates/aienos-infer/src/lib.rs @@ -0,0 +1,27 @@ +#![no_std] +#![forbid(unsafe_code)] +// Block loops mirror ggml index arithmetic; as_chunks/is_multiple_of are too +// new for this workspace to rely on. +#![allow( + clippy::needless_range_loop, + clippy::chunks_exact_to_as_chunks, + clippy::manual_is_multiple_of +)] + +//! Native inference ingestion (aienos#34 lane 1): a bounded GGUF v3 reader +//! and the ggml block dequantizers (Q4_K, Q6_K and the plain float types) +//! needed to load Llama-3.2-1B-Instruct-Q4_K_M. +//! +//! Everything works on a `&[u8]` slice. Every read is length checked and +//! hostile input yields a [`GgufError`], never a panic. Dequantizers are +//! scalar and written for correctness first. + +extern crate alloc; +#[cfg(test)] +extern crate std; + +pub mod gguf; +pub mod half; +pub mod quant; + +pub use gguf::{ArrayView, GgmlType, Gguf, GgufError, TensorInfo, Value, ValueType}; diff --git a/crates/aienos-infer/src/quant.rs b/crates/aienos-infer/src/quant.rs new file mode 100644 index 00000000..1f453d2c --- /dev/null +++ b/crates/aienos-infer/src/quant.rs @@ -0,0 +1,264 @@ +//! ggml block dequantizers (scalar reference implementations). +//! +//! Formulas follow ggml's `dequantize_row_q4_K` / `dequantize_row_q6_K` +//! (ggml-quants.c). Both formats pack 256 weights per super-block. + +use crate::gguf::GgmlType; +use crate::half::f16_to_f32; + +/// Weights per K-quant super-block. +pub const QK_K: usize = 256; +/// Bytes per Q4_K block: f16 d, f16 dmin, 12 bytes scales/mins, 128 bytes nibbles. +pub const Q4K_BYTES: usize = 144; +/// Bytes per Q6_K block: 128 ql, 64 qh, 16 i8 scales, f16 d. +pub const Q6K_BYTES: usize = 210; + +/// Reasons a dequantization request is refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QuantError { + /// Type has no dequantizer here. + Unsupported(GgmlType), + /// Source length is not the whole number of blocks that `out` needs. + BadLength, +} + +fn rd_f16(b: &[u8], at: usize) -> f32 { + f16_to_f32(u16::from_le_bytes([b[at], b[at + 1]])) +} + +/// 6-bit scale and min for sub-block `j` (0..8) from the 12 packed bytes. +fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) { + if j < 4 { + (q[j] & 63, q[j + 4] & 63) + } else { + ( + (q[j + 4] & 0x0f) | ((q[j - 4] >> 6) << 4), + (q[j + 4] >> 4) | ((q[j] >> 6) << 4), + ) + } +} + +/// Dequantize one Q4_K block (144 bytes) into 256 floats. +pub fn dequant_q4k_block(block: &[u8; Q4K_BYTES], out: &mut [f32; QK_K]) { + let d = rd_f16(block, 0); + let dmin = rd_f16(block, 2); + let scales = &block[4..16]; + let qs = &block[16..144]; + for j in 0..4 { + let (sc1, m1) = scale_min_k4(2 * j, scales); + let (sc2, m2) = scale_min_k4(2 * j + 1, scales); + let (d1, mn1) = (d * sc1 as f32, dmin * m1 as f32); + let (d2, mn2) = (d * sc2 as f32, dmin * m2 as f32); + let q = &qs[32 * j..32 * j + 32]; + let o = &mut out[64 * j..64 * j + 64]; + for l in 0..32 { + o[l] = d1 * (q[l] & 0x0f) as f32 - mn1; + o[l + 32] = d2 * (q[l] >> 4) as f32 - mn2; + } + } +} + +/// Dequantize one Q6_K block (210 bytes) into 256 floats. +pub fn dequant_q6k_block(block: &[u8; Q6K_BYTES], out: &mut [f32; QK_K]) { + let d = rd_f16(block, 208); + for half in 0..2 { + let ql = &block[64 * half..64 * half + 64]; + let qh = &block[128 + 32 * half..128 + 32 * half + 32]; + let sc = &block[192 + 8 * half..192 + 8 * half + 8]; + let o = &mut out[128 * half..128 * half + 128]; + for l in 0..32 { + let is = l / 16; + let h = qh[l]; + let q1 = ((ql[l] & 0x0f) | ((h & 3) << 4)) as i32 - 32; + let q2 = ((ql[l + 32] & 0x0f) | (((h >> 2) & 3) << 4)) as i32 - 32; + let q3 = ((ql[l] >> 4) | (((h >> 4) & 3) << 4)) as i32 - 32; + let q4 = ((ql[l + 32] >> 4) | (((h >> 6) & 3) << 4)) as i32 - 32; + o[l] = d * (sc[is] as i8) as f32 * q1 as f32; + o[l + 32] = d * (sc[is + 2] as i8) as f32 * q2 as f32; + o[l + 64] = d * (sc[is + 4] as i8) as f32 * q3 as f32; + o[l + 96] = d * (sc[is + 6] as i8) as f32 * q4 as f32; + } + } +} + +fn as_block(b: &[u8]) -> &[u8; N] { + // Callers pass chunks_exact(N) slices, so the length is always N. + b.try_into().expect("chunk length is N") +} + +/// Dot product of one Q4_K block with 256 f32 activations (dequantize, then +/// accumulate in f32; scalar reference, not bit-identical to ggml's q8 path). +pub fn dot_q4k_f32(block: &[u8; Q4K_BYTES], x: &[f32; QK_K]) -> f32 { + let mut w = [0f32; QK_K]; + dequant_q4k_block(block, &mut w); + w.iter().zip(x).map(|(a, b)| a * b).sum() +} + +/// Dot product of one Q6_K block with 256 f32 activations. +pub fn dot_q6k_f32(block: &[u8; Q6K_BYTES], x: &[f32; QK_K]) -> f32 { + let mut w = [0f32; QK_K]; + dequant_q6k_block(block, &mut w); + w.iter().zip(x).map(|(a, b)| a * b).sum() +} + +/// Dot of a whole quantized row (`src`, `x.len()` weights) with `x`. +pub fn dot_row(ty: GgmlType, src: &[u8], x: &[f32]) -> Result { + let (bw, bb) = ty.block(); + if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) { + return Err(QuantError::Unsupported(ty)); + } + if x.len() % bw != 0 || src.len() != x.len() / bw * bb { + return Err(QuantError::BadLength); + } + let mut acc = 0f32; + for (blk, xs) in src.chunks_exact(bb).zip(x.chunks_exact(QK_K)) { + let xs: &[f32; QK_K] = xs.try_into().expect("chunk is QK_K"); + acc += if ty == GgmlType::Q4K { + dot_q4k_f32(as_block(blk), xs) + } else { + dot_q6k_f32(as_block(blk), xs) + }; + } + Ok(acc) +} + +/// Dequantize `out.len()` weights of type `ty` from `src` (whole blocks). +pub fn dequantize(ty: GgmlType, src: &[u8], out: &mut [f32]) -> Result<(), QuantError> { + let (bw, bb) = ty.block(); + if out.len() % bw != 0 || src.len() != out.len() / bw * bb { + return Err(QuantError::BadLength); + } + match ty { + GgmlType::Q4K => { + for (blk, o) in src.chunks_exact(bb).zip(out.chunks_exact_mut(QK_K)) { + dequant_q4k_block(as_block(blk), o.try_into().expect("chunk is QK_K")); + } + } + GgmlType::Q6K => { + for (blk, o) in src.chunks_exact(bb).zip(out.chunks_exact_mut(QK_K)) { + dequant_q6k_block(as_block(blk), o.try_into().expect("chunk is QK_K")); + } + } + other => { + if !crate::gguf::plain_to_f32(other, src, out) { + return Err(QuantError::Unsupported(other)); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ONE: [u8; 2] = [0x00, 0x3c]; // f16 1.0 + + #[test] + fn q4k_hand_block() { + // d=1, dmin=1. Sub-block j has scale j+1 and min j (all < 16 so they + // sit in the plain low 6 bits of bytes 0..8). Nibble pattern: low + // nibble = l%16, high nibble = 15 - l%16. + let mut b = [0u8; Q4K_BYTES]; + b[0..2].copy_from_slice(&ONE); + b[2..4].copy_from_slice(&ONE); + for j in 0..4 { + b[4 + j] = (j + 1) as u8; // scales 1..4 for sub-blocks 0..4 + b[8 + j] = j as u8; // mins 0..3 + } + // sub-blocks 4..8: low nibble of bytes 8..12 = scale, high = min, and + // the top two bits of bytes 0..4 / 4..8 are 0 so no extension. + for j in 4..8 { + b[8 + j] = ((j + 1) as u8) | ((j as u8) << 4); + } + for l in 0..128 { + let lo = (l % 16) as u8; + b[16 + l] = lo | ((15 - lo) << 4); + } + let mut out = [0f32; QK_K]; + dequant_q4k_block(&b, &mut out); + for sb in 0..8 { + let j = sb / 2; + let (sc, mn) = (sb + 1, sb); + for l in 0..32 { + let lo = (l % 16) as f32; + let q = if sb % 2 == 0 { lo } else { 15.0 - lo }; + let expect = sc as f32 * q - mn as f32; + assert_eq!(out[32 * sb + l], expect, "sb {sb} l {l} (j {j})"); + } + } + } + + #[test] + fn q4k_scale_extension_bits() { + // Sub-block 4: scale = 0xf | (3 << 4) = 63 (byte 8 low nibble + byte 0 >> 6); + // min = 0x2 | (2 << 4) = 34 (byte 8 high nibble + byte 4 >> 6). + let mut b = [0u8; Q4K_BYTES]; + b[0..2].copy_from_slice(&ONE); + b[2..4].copy_from_slice(&ONE); + b[4] = 3 << 6; // byte 0 of scales: top bits -> scale high of sb4 + b[8] = 2 << 6; // byte 4 of scales: top bits -> min high of sb4 + b[12] = 0x0f | (0x2 << 4); + for q in b[16..].iter_mut() { + *q = 0x11; + } + let mut out = [0f32; QK_K]; + dequant_q4k_block(&b, &mut out); + // sb4 is the low half of j=2 qs; nibble 1 -> 63*1 - 42. + assert_eq!(out[128], 63.0 - 34.0); + // sb0 has scale 0, min 0 -> exactly 0. + assert_eq!(out[0], 0.0); + } + + #[test] + fn q6k_hand_block() { + // d=1, all scales 1, ql nibbles = 0x0, qh = 0 -> q = -32 everywhere + // for low nibbles; set specific positions to check the bit layout. + let mut b = [0u8; Q6K_BYTES]; + b[208..210].copy_from_slice(&ONE); + for i in 0..16 { + b[192 + i] = 1; + } + let mut out = [0f32; QK_K]; + dequant_q6k_block(&b, &mut out); + assert!(out.iter().all(|&v| v == -32.0)); + // l=0 of the first half: ql[0]=0x5a, qh[0]=0b11_10_01_00. + b[0] = 0x5a; + b[128] = 0b1110_0100; + dequant_q6k_block(&b, &mut out); + assert_eq!(out[0], 0xa as f32 - 32.0); // q1 + assert_eq!(out[64], ((0x5) | (2 << 4)) as f32 - 32.0); // q3: qh bits 4..6 = 2 + assert_eq!(out[32], 16.0 - 32.0); // q2: low nibble 0, qh bits 2..4 = 1 + assert_eq!(out[96], 48.0 - 32.0); // q4: low nibble of ql[32]=0, qh bits 6..8 = 3 + } + + #[test] + fn q6k_scales_are_signed_and_per_16() { + let mut b = [0u8; Q6K_BYTES]; + b[208..210].copy_from_slice(&ONE); + for i in 0..16 { + b[192 + i] = (i as i8 - 8) as u8; + } + // ql/qh zero -> q=-32; weight p has scale index p/16. + let mut out = [0f32; QK_K]; + dequant_q6k_block(&b, &mut out); + for p in 0..QK_K { + assert_eq!(out[p], (p / 16) as f32 * -32.0 + 8.0 * 32.0, "p {p}"); + } + } + + #[test] + fn length_checks() { + let mut out = [0f32; QK_K]; + assert_eq!( + dequantize(GgmlType::Q4K, &[0u8; 143], &mut out), + Err(QuantError::BadLength) + ); + assert_eq!( + dequantize(GgmlType::Q5K, &[0u8; 176], &mut out), + Err(QuantError::Unsupported(GgmlType::Q5K)) + ); + let x = [1f32; QK_K]; + assert_eq!(dot_row(GgmlType::Q4K, &[0u8; Q4K_BYTES], &x), Ok(0.0)); + } +} diff --git a/crates/aienos-infer/tests/fixtures/PROVENANCE.md b/crates/aienos-infer/tests/fixtures/PROVENANCE.md new file mode 100644 index 00000000..5b4156da --- /dev/null +++ b/crates/aienos-infer/tests/fixtures/PROVENANCE.md @@ -0,0 +1,13 @@ +# Fixture provenance + +q4k.bin / q6k.bin: 4 blocks each from two tensors of Llama-3.2-1B-Instruct-Q4_K_M.gguf +(sha256 3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1). +Absolute file offsets: Q4_K 223309856 (blk.0.attn_k) and 798257184 (blk.15.ffn_up); +Q6_K 228626464 (blk.0.attn_v) and 775049248 (blk.15.ffn_down). +q4k.f32 / q6k.f32: output of ggml dequantize_row_q4_K / dequantize_row_q6_K on those blocks. + +Reference library: /home/drakestapleton/.lmstudio/extensions/backends/llama.cpp-linux-arm64-2.33.0/libggml-base.so +llama.cpp backend version 2.33.0 (LM Studio), sha256 3a9c7bf9d5696414839ec441958c469b947437bf1db2f4468272e3731b30378e + +Regenerate: make -C crates/aienos-infer/tests/fixtures/gen regen +Generator is C only (gen/gen.c, no Python). Needs the model file and the library above. diff --git a/crates/aienos-infer/tests/fixtures/gen/Makefile b/crates/aienos-infer/tests/fixtures/gen/Makefile new file mode 100644 index 00000000..8883d3f2 --- /dev/null +++ b/crates/aienos-infer/tests/fixtures/gen/Makefile @@ -0,0 +1,8 @@ +# Rebuild the ggml golden fixtures: `make -C crates/aienos-infer/tests/fixtures/gen regen` +GGML_DIR ?= /home/drakestapleton/.lmstudio/extensions/backends/llama.cpp-linux-arm64-2.33.0 +gen: gen.c + $(CC) -O1 gen.c -o gen -L$(GGML_DIR) -lggml-base -Wl,-rpath,$(GGML_DIR) +regen: gen + ./gen .. +clean: + rm -f gen diff --git a/crates/aienos-infer/tests/fixtures/gen/gen.c b/crates/aienos-infer/tests/fixtures/gen/gen.c new file mode 100644 index 00000000..92649c67 --- /dev/null +++ b/crates/aienos-infer/tests/fixtures/gen/gen.c @@ -0,0 +1,19 @@ +/* Regenerates ../q4k.* and ../q6k.* : blocks cut from the real GGUF plus the + * output of ggml dequantize_row_q4_K/q6_K. Run via ../../../tools or `make -C gen`. + * Usage: gen */ +#include +#include +#include +extern void dequantize_row_q4_K(const void*, float*, int64_t); +extern void dequantize_row_q6_K(const void*, float*, int64_t); +static void go(const char*f,int q6,long offs[2],const char*pfx){ + int bs=q6?210:144; int nb=4; char n[256]; + snprintf(n,256,"%s.bin",pfx); FILE*o=fopen(n,"wb"); + snprintf(n,256,"%s.f32",pfx); FILE*r=fopen(n,"wb"); + FILE*in=fopen(f,"rb"); + for(int t=0;t<2;t++){ fseek(in,offs[t],SEEK_SET); unsigned char*buf=malloc(bs*nb); fread(buf,bs,nb,in); fwrite(buf,bs,nb,o); + float*y=malloc(256*nb*4); if(q6)dequantize_row_q6_K(buf,y,256*nb); else dequantize_row_q4_K(buf,y,256*nb); fwrite(y,4,256*nb,r);} + fclose(o);fclose(r);fclose(in);} +int main(int argc,char**argv){const char*d=argc>1?argv[1]:".";const char*f="/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf"; + long a[2]={223309856,798257184}, b[2]={228626464,775049248}; + char p4[300],p6[300];snprintf(p4,300,"%s/q4k",d);snprintf(p6,300,"%s/q6k",d);go(f,0,a,p4);go(f,1,b,p6);return 0;} diff --git a/crates/aienos-infer/tests/fixtures/q4k.bin b/crates/aienos-infer/tests/fixtures/q4k.bin new file mode 100644 index 00000000..fbfa7cb7 Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/q4k.bin differ diff --git a/crates/aienos-infer/tests/fixtures/q4k.f32 b/crates/aienos-infer/tests/fixtures/q4k.f32 new file mode 100644 index 00000000..a86a166a Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/q4k.f32 differ diff --git a/crates/aienos-infer/tests/fixtures/q6k.bin b/crates/aienos-infer/tests/fixtures/q6k.bin new file mode 100644 index 00000000..ae741250 Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/q6k.bin differ diff --git a/crates/aienos-infer/tests/fixtures/q6k.f32 b/crates/aienos-infer/tests/fixtures/q6k.f32 new file mode 100644 index 00000000..ba6cab26 Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/q6k.f32 differ diff --git a/crates/aienos-infer/tests/golden.rs b/crates/aienos-infer/tests/golden.rs new file mode 100644 index 00000000..ff533da5 --- /dev/null +++ b/crates/aienos-infer/tests/golden.rs @@ -0,0 +1,656 @@ +//! Golden and hostile-input tests for the GGUF reader and dequantizers. +//! +//! Real-file tests read the frozen Llama-3.2-1B-Instruct-Q4_K_M model and are +//! skipped with a message when it is absent, so CI without the model stays +//! green. Fixtures in `tests/fixtures` were produced by ggml's own +//! `dequantize_row_q4_K` / `dequantize_row_q6_K` (LM Studio llama.cpp +//! backend 2.33.0 libggml-base.so) from blocks cut out of the real file. + +#![allow(clippy::chunks_exact_to_as_chunks, clippy::manual_is_multiple_of)] + +use aienos_infer::quant::{dequantize, dot_q4k_f32, dot_q6k_f32, dot_row, QK_K}; +use aienos_infer::*; +use std::collections::BTreeMap; + +const MODEL: &str = "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf"; +const META: &str = "/home/drakestapleton/models/aien-mail/.cache/huggingface/download/Llama-3.2-1B-Instruct-Q4_K_M.gguf.metadata"; + +fn model() -> Option> { + match std::fs::read(MODEL) { + Ok(b) => Some(b), + Err(e) => { + eprintln!("SKIP: model file {MODEL} not readable ({e})"); + None + } + } +} + +fn fx(name: &str) -> Vec { + std::fs::read(format!( + "{}/tests/fixtures/{name}", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap() +} + +fn f32s(b: &[u8]) -> Vec { + b.chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +// ---------------------------------------------------------------- real file + +#[test] +fn real_header_matches_known_facts() { + let Some(b) = model() else { return }; + let g = Gguf::parse(&b).unwrap(); + assert_eq!(g.version, 3); + assert_eq!(g.alignment, 32); + assert_eq!(g.data_start % 32, 0); + assert_eq!(g.architecture().unwrap(), "llama"); + let p = g.llama_params().unwrap(); + // 16 layers, 2048 dim, 32 heads, 8 kv heads, 8192 ffn, 128256 vocab are + // the published Llama-3.2-1B shape (config.json); the values here are + // read from the file and asserted equal to those facts. + assert_eq!(p.block_count, 16); + assert_eq!(p.embedding_length, 2048); + assert_eq!(p.head_count, 32); + assert_eq!(p.head_count_kv, 8); + assert_eq!(p.feed_forward_length, 8192); + assert_eq!(p.vocab_size, 128256); + assert_eq!(p.context_length, 131072); + assert_eq!(p.rope_freq_base, 500000.0); + assert_eq!(p.rms_norm_eps, 1e-5); + let t = g.tokenizer().unwrap(); + assert_eq!(t.tokens.len(), 128256); + assert_eq!(t.token_type.unwrap().len(), 128256); + assert_eq!(t.merges.unwrap().len(), 280147); + assert!(t.scores.is_none(), "this file has no tokenizer.ggml.scores"); + assert_eq!(t.bos_id, Some(128000)); + assert_eq!(t.eos_id, Some(128009)); + let toks: Vec<&str> = t.tokens.strings().collect(); + assert_eq!(toks.len(), 128256); + assert_eq!(toks[128000], "<|begin_of_text|>"); + assert_eq!(toks[128009], "<|eot_id|>"); + assert_eq!(t.token_type.unwrap().i32s().count(), 128256); + assert_eq!(t.merges.unwrap().strings().count(), 280147); +} + +#[test] +fn real_file_matches_hf_metadata_hash() { + let Ok(meta) = std::fs::read_to_string(META) else { + eprintln!("SKIP: HF metadata file absent"); + return; + }; + let Some(b) = model() else { return }; + // Line 2 of the HF cache metadata is the file's sha256 (etag). + let want = meta.lines().nth(1).unwrap().trim().to_string(); + assert_eq!(want.len(), 64); + let out = std::process::Command::new("sha256sum").arg(MODEL).output(); + let Ok(out) = out else { + eprintln!("SKIP: no sha256sum"); + return; + }; + let got = String::from_utf8_lossy(&out.stdout); + assert_eq!(got.split_whitespace().next().unwrap(), want); + assert_eq!(b.len(), 807_694_368); +} + +#[test] +fn real_type_histogram_and_table_sanity() { + let Some(b) = model() else { return }; + let g = Gguf::parse(&b).unwrap(); + let mut h: BTreeMap = BTreeMap::new(); + for t in g.tensors() { + *h.entry(t.ty).or_default() += 1; + } + assert_eq!(h[&GgmlType::F32], 34); + assert_eq!(h[&GgmlType::Q4K], 96); + assert_eq!(h[&GgmlType::Q6K], 17); + assert_eq!(h.len(), 3); + assert_eq!(g.tensors().len(), 147); + // Every range inside the file; sizes match block math; and tensors are + // packed back to back at the alignment, which independently confirms the + // per-type block sizes (a wrong size would shift every following offset). + let mut v: Vec<&TensorInfo> = g.tensors().iter().collect(); + v.sort_by_key(|t| t.offset); + let mut expect = 0u64; + for t in &v { + assert_eq!(t.offset, expect, "{}", t.name); + let (bw, bb) = t.ty.block(); + assert_eq!(t.n_bytes, t.n_elements / bw as u64 * bb as u64); + assert_eq!( + t.row_bytes() * t.dims[1..].iter().product::(), + t.n_bytes + ); + assert!(g.data_start as u64 + t.offset + t.n_bytes <= b.len() as u64); + assert_eq!(g.tensor_data(t).len() as u64, t.n_bytes); + expect = (t.offset + t.n_bytes + 31) & !31; + } + assert_eq!( + g.data_start as u64 + v.last().map(|t| t.offset + t.n_bytes).unwrap(), + b.len() as u64 + ); + let e = g.tensor("token_embd.weight").unwrap(); + assert_eq!((e.ty, e.dims[0], e.dims[1]), (GgmlType::Q6K, 2048, 128256)); + assert!( + g.tensor("output.weight").is_none(), + "output is tied to token_embd" + ); +} + +#[test] +fn real_layer0_dequantizes_to_sane_values() { + let Some(b) = model() else { return }; + let g = Gguf::parse(&b).unwrap(); + for t in g.tensors().iter().filter(|t| t.name.starts_with("blk.0.")) { + let mut out = vec![0f32; t.n_elements as usize]; + dequantize(t.ty, g.tensor_data(t), &mut out).unwrap(); + assert!(out.iter().all(|v| v.is_finite()), "{}", t.name); + let max = out.iter().fold(0f32, |m, v| m.max(v.abs())); + assert!(max > 0.0 && max < 100.0, "{} max {max}", t.name); + } +} + +// ---------------------------------------------------------------- ggml cross-check + +#[test] +fn q4k_matches_ggml_bit_for_bit() { + let bin = fx("q4k.bin"); + let want = f32s(&fx("q4k.f32")); + let mut got = vec![0f32; want.len()]; + dequantize(GgmlType::Q4K, &bin, &mut got).unwrap(); + for (i, (a, b)) in got.iter().zip(&want).enumerate() { + assert_eq!(a.to_bits(), b.to_bits(), "weight {i}: {a} vs ggml {b}"); + } +} + +#[test] +fn q6k_matches_ggml_bit_for_bit() { + let bin = fx("q6k.bin"); + let want = f32s(&fx("q6k.f32")); + let mut got = vec![0f32; want.len()]; + dequantize(GgmlType::Q6K, &bin, &mut got).unwrap(); + for (i, (a, b)) in got.iter().zip(&want).enumerate() { + assert_eq!(a.to_bits(), b.to_bits(), "weight {i}: {a} vs ggml {b}"); + } +} + +#[test] +fn dot_helpers_match_dequant_then_dot() { + let bin = fx("q4k.bin"); + let w = f32s(&fx("q4k.f32")); + let x: Vec = (0..QK_K) + .map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.25) + .collect(); + let xa: &[f32; QK_K] = x.as_slice().try_into().unwrap(); + let blk: &[u8; 144] = bin[..144].try_into().unwrap(); + let want: f32 = w[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); + assert_eq!(dot_q4k_f32(blk, xa), want); + let bin6 = fx("q6k.bin"); + let w6 = f32s(&fx("q6k.f32")); + let blk6: &[u8; 210] = bin6[..210].try_into().unwrap(); + let want6: f32 = w6[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); + assert_eq!(dot_q6k_f32(blk6, xa), want6); + // Row of 4 blocks. + let x4: Vec = (0..4 * QK_K).map(|i| (i % 5) as f32 - 2.0).collect(); + let w4: f32 = w[..4 * QK_K].iter().zip(&x4).map(|(a, b)| a * b).sum(); + let got = dot_row(GgmlType::Q4K, &bin[..4 * 144], &x4).unwrap(); + assert!( + (got - w4).abs() <= 1e-3 * w4.abs().max(1.0), + "{got} vs {w4}" + ); +} + +// ---------------------------------------------------------------- round trip + +fn f32_to_f16(v: f32) -> u16 { + // Round to nearest, normal range only (test scales are well inside it). + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32 - 127 + 15; + let man = b & 0x7f_ffff; + if v == 0.0 { + return sign; + } + assert!((1..31).contains(&exp), "out of f16 normal range: {v}"); + let mut h = ((exp as u32) << 10) | (man >> 13); + if man & 0x1000 != 0 { + h += 1; // carries into the exponent correctly + } + sign | h as u16 +} + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f32 { + (self.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + } +} + +/// Simple reference Q4_K quantizer: 8 sub-blocks of 32, each w = d*sc*q - dmin*m. +fn quantize_q4k(x: &[f32; QK_K]) -> [u8; 144] { + let mut ds = [0f32; 8]; + let mut ms = [0f32; 8]; + for j in 0..8 { + let s = &x[32 * j..32 * j + 32]; + let mn = s.iter().cloned().fold(0f32, f32::min); + let mx = s.iter().cloned().fold(0f32, f32::max); + ms[j] = -mn; + ds[j] = (mx - mn) / 15.0; + } + let dmax = ds.iter().cloned().fold(0f32, f32::max); + let mmax = ms.iter().cloned().fold(0f32, f32::max); + let d16 = f32_to_f16(dmax / 63.0); + let m16 = f32_to_f16(mmax / 63.0); + let d = aienos_infer::half::f16_to_f32(d16); + let dmin = aienos_infer::half::f16_to_f32(m16); + let mut sc = [0u8; 8]; + let mut mn6 = [0u8; 8]; + for j in 0..8 { + sc[j] = if d > 0.0 { + (ds[j] / d).round().clamp(0.0, 63.0) as u8 + } else { + 0 + }; + mn6[j] = if dmin > 0.0 { + (ms[j] / dmin).round().clamp(0.0, 63.0) as u8 + } else { + 0 + }; + } + let mut b = [0u8; 144]; + b[0..2].copy_from_slice(&d16.to_le_bytes()); + b[2..4].copy_from_slice(&m16.to_le_bytes()); + // Pack 6-bit scales/mins (inverse of get_scale_min_k4). + for j in 0..4 { + b[4 + j] = sc[j] | ((sc[j + 4] >> 4) << 6); + b[8 + j] = mn6[j] | ((mn6[j + 4] >> 4) << 6); + b[12 + j] = (sc[j + 4] & 0xf) | ((mn6[j + 4] & 0xf) << 4); + } + for j in 0..8 { + let step = d * sc[j] as f32; + let off = dmin * mn6[j] as f32; + for l in 0..32 { + let q = if step > 0.0 { + ((x[32 * j + l] + off) / step).round().clamp(0.0, 15.0) as u8 + } else { + 0 + }; + // sub-blocks 2k (low nibble) and 2k+1 (high nibble) share 32 bytes. + let byte = &mut b[16 + 32 * (j / 2) + l]; + if j % 2 == 0 { + *byte |= q + } else { + *byte |= q << 4 + } + } + } + b +} + +/// Simple reference Q6_K quantizer: 16 sub-blocks of 16, w = d*sc*(q-32). +fn quantize_q6k(x: &[f32; QK_K]) -> [u8; 210] { + let mut sub = [0f32; 16]; + for j in 0..16 { + sub[j] = x[16 * j..16 * j + 16] + .iter() + .fold(0f32, |m, v| m.max(v.abs())) + / 32.0; + } + let smax = sub.iter().cloned().fold(0f32, f32::max); + let d16 = f32_to_f16(smax / 127.0); + let d = aienos_infer::half::f16_to_f32(d16); + let mut b = [0u8; 210]; + b[208..210].copy_from_slice(&d16.to_le_bytes()); + let mut sc = [0i8; 16]; + for j in 0..16 { + sc[j] = if d > 0.0 { + (sub[j] / d).round().clamp(0.0, 127.0) as i8 + } else { + 0 + }; + b[192 + j] = sc[j] as u8; + } + let q = |p: usize| -> u8 { + let s = d * sc[p / 16] as f32; + if s > 0.0 { + ((x[p] / s).round() + 32.0).clamp(0.0, 63.0) as u8 + } else { + 32 + } + }; + for h in 0..2 { + for l in 0..32 { + let base = 128 * h; + let (q1, q2, q3, q4) = ( + q(base + l), + q(base + l + 32), + q(base + l + 64), + q(base + l + 96), + ); + b[64 * h + l] = (q1 & 0xf) | ((q3 & 0xf) << 4); + b[64 * h + l + 32] = (q2 & 0xf) | ((q4 & 0xf) << 4); + b[128 + 32 * h + l] = + (q1 >> 4) | ((q2 >> 4) << 2) | ((q3 >> 4) << 4) | ((q4 >> 4) << 6); + } + } + b +} + +fn max_round_trip_err(ty: GgmlType, trials: usize) -> f32 { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let mut worst = 0f32; + for _ in 0..trials { + let mut x = [0f32; QK_K]; + for v in x.iter_mut() { + *v = rng.unit(); + } + let mut y = [0f32; QK_K]; + match ty { + GgmlType::Q4K => dequantize(ty, &quantize_q4k(&x), &mut y).unwrap(), + _ => dequantize(ty, &quantize_q6k(&x), &mut y).unwrap(), + } + for (a, b) in x.iter().zip(&y) { + worst = worst.max((a - b).abs()); + } + } + worst +} + +#[test] +fn q4k_round_trip_error_bound() { + // x in [-1,1]: a 4-bit step over a sub-block range <= 2 is 2/15 = 0.133, + // so half-step 0.067 plus 6-bit scale/min rounding stays under 0.1. + let worst = max_round_trip_err(GgmlType::Q4K, 200); + eprintln!("q4k round trip max abs error {worst}"); + assert!(worst < 0.1, "{worst}"); +} + +#[test] +fn q6k_round_trip_error_bound() { + // 6-bit: step = maxabs/32 <= 1/32. The grid is -32..31, so +maxabs clamps + // to 31 (one full step, 0.031) plus half-step rounding 0.016 -> under 0.05. + let worst = max_round_trip_err(GgmlType::Q6K, 200); + eprintln!("q6k round trip max abs error {worst}"); + assert!(worst < 0.05, "{worst}"); +} + +#[test] +fn round_trip_exact_when_grid_aligned() { + // Values that lie exactly on the Q4_K grid must come back exactly: + // d = dmin = 1/64 scales are exact in f16. + let mut x = [0f32; QK_K]; + for (i, v) in x.iter_mut().enumerate() { + *v = (i % 16) as f32; // each sub-block spans 0..15: sc=1*d, m=0 + } + // d = 15/15 = 1 -> scale 63 needs d=1/63 which is inexact; use the + // hand-built path instead: d=1, sc=1, min=0. + let mut b = [0u8; 144]; + b[0..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for j in 0..4 { + b[4 + j] = 1; + } + for j in 0..4 { + b[12 + j] = 1; + } + for l in 0..128 { + let lo = (l % 16) as u8; + b[16 + l] = lo | (lo << 4); + } + let mut y = [0f32; QK_K]; + dequantize(GgmlType::Q4K, &b, &mut y).unwrap(); + assert_eq!(x.to_vec(), y.to_vec()); +} + +// ---------------------------------------------------------------- hostile input + +/// Minimal valid GGUF builder for hostile-input tests. +struct B(Vec); +impl B { + fn new(n_tensors: u64, n_kv: u64) -> Self { + let mut v = b"GGUF".to_vec(); + v.extend(3u32.to_le_bytes()); + v.extend(n_tensors.to_le_bytes()); + v.extend(n_kv.to_le_bytes()); + B(v) + } + fn s(&mut self, s: &str) { + self.0.extend((s.len() as u64).to_le_bytes()); + self.0.extend(s.as_bytes()); + } + fn kv_u32(&mut self, k: &str, v: u32) { + self.s(k); + self.0.extend(4u32.to_le_bytes()); + self.0.extend(v.to_le_bytes()); + } + fn tensor(&mut self, name: &str, dims: &[u64], ty: u32, off: u64) { + self.s(name); + self.0.extend((dims.len() as u32).to_le_bytes()); + for d in dims { + self.0.extend(d.to_le_bytes()); + } + self.0.extend(ty.to_le_bytes()); + self.0.extend(off.to_le_bytes()); + } + fn pad_data(mut self, n: usize) -> Vec { + while self.0.len() % 32 != 0 { + self.0.push(0); + } + self.0.extend(std::iter::repeat_n(0u8, n)); + self.0 + } +} + +fn good_small() -> Vec { + let mut b = B::new(1, 2); + b.kv_u32("a.b", 7); + b.s("tokens"); + b.0.extend(9u32.to_le_bytes()); // array + b.0.extend(8u32.to_le_bytes()); // of string + b.0.extend(2u64.to_le_bytes()); + b.s("hi"); + b.s("yo"); + b.tensor("w", &[256], 12, 0); + b.pad_data(144) +} + +#[test] +fn small_good_file_parses() { + let f = good_small(); + let g = Gguf::parse(&f).unwrap(); + assert_eq!(g.u32_key("a.b").unwrap(), 7); + let toks: Vec<_> = g.array_key("tokens").unwrap().strings().collect(); + assert_eq!(toks, ["hi", "yo"]); + assert_eq!(g.tensor("w").unwrap().n_bytes, 144); + assert_eq!(g.u32_key("nope"), Err(GgufError::Missing("nope"))); + assert_eq!(g.str_key("a.b"), Err(GgufError::WrongType("a.b"))); +} + +#[test] +fn every_truncation_is_an_error_not_a_panic() { + let f = good_small(); + for n in 0..f.len() { + assert!(Gguf::parse(&f[..n]).is_err(), "len {n} should fail"); + } + // Real file: all short lengths plus a strided sweep through the header. + if let Some(b) = model() { + let g = Gguf::parse(&b).unwrap(); + for n in 0..3000 { + assert!(Gguf::parse(&b[..n]).is_err(), "len {n}"); + } + let mut n = 3000; + while n < g.data_start { + assert!(Gguf::parse(&b[..n]).is_err(), "len {n}"); + n += 99_991; + } + // Cutting inside the tensor data must fail the range check. + assert_eq!( + Gguf::parse(&b[..b.len() - 1]).unwrap_err(), + GgufError::TensorOutOfRange + ); + assert!(Gguf::parse(&b[..g.data_start]).is_err()); + } +} + +#[test] +fn absurd_counts_and_bad_fields() { + let mut f = B::new(u64::MAX, 0).0; + assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); + f = B::new(0, u64::MAX / 2).0; + assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); + f = B::new(1_000_000, 0).pad_data(64); + assert_eq!(Gguf::parse(&f).unwrap_err(), GgufError::TooMany); + let mut bad_magic = good_small(); + bad_magic[0] = b'X'; + assert_eq!(Gguf::parse(&bad_magic).unwrap_err(), GgufError::BadMagic); + let mut bad_ver = good_small(); + bad_ver[4] = 2; + assert_eq!( + Gguf::parse(&bad_ver).unwrap_err(), + GgufError::UnsupportedVersion(2) + ); + + // Offset past end. + let mut b = B::new(1, 0); + b.tensor("w", &[256], 12, 1 << 40); + assert_eq!( + Gguf::parse(&b.pad_data(144)).unwrap_err(), + GgufError::TensorOutOfRange + ); + // Offset + size overflow u64. + let mut b = B::new(1, 0); + b.tensor("w", &[256], 12, u64::MAX - 8); + assert_eq!( + Gguf::parse(&b.pad_data(144)).unwrap_err(), + GgufError::Overflow + ); + // Misaligned offset. + let mut b = B::new(1, 0); + b.tensor("w", &[256], 12, 16); + assert_eq!( + Gguf::parse(&b.pad_data(400)).unwrap_err(), + GgufError::TensorOutOfRange + ); + // Dimension product overflow. + let mut b = B::new(1, 0); + b.tensor("w", &[1 << 40, 1 << 40], 0, 0); + assert_eq!( + Gguf::parse(&b.pad_data(8)).unwrap_err(), + GgufError::Overflow + ); + // Row not a whole number of blocks. + let mut b = B::new(1, 0); + b.tensor("w", &[255], 12, 0); + assert_eq!( + Gguf::parse(&b.pad_data(400)).unwrap_err(), + GgufError::BadDims + ); + // 0 and 5 dims. + let mut b = B::new(1, 0); + b.tensor("w", &[], 0, 0); + assert_eq!(Gguf::parse(&b.pad_data(8)).unwrap_err(), GgufError::BadDims); + let mut b = B::new(1, 0); + b.tensor("w", &[1, 1, 1, 1, 1], 0, 0); + assert_eq!(Gguf::parse(&b.pad_data(8)).unwrap_err(), GgufError::BadDims); + // Unknown tensor type, unknown kv type. + let mut b = B::new(1, 0); + b.tensor("w", &[32], 99, 0); + assert_eq!( + Gguf::parse(&b.pad_data(8)).unwrap_err(), + GgufError::UnsupportedType(99) + ); + let mut b = B::new(0, 1); + b.s("k"); + b.0.extend(77u32.to_le_bytes()); + assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::BadValueType(77)); + // Zero and non power of two alignment. + for a in [0u32, 3] { + let mut b = B::new(0, 1); + b.kv_u32("general.alignment", a); + assert_eq!( + Gguf::parse(&b.pad_data(8)).unwrap_err(), + GgufError::BadAlignment + ); + } + // Huge string length, huge array length, nested array. + let mut b = B::new(0, 1); + b.0.extend(u64::MAX.to_le_bytes()); + assert!(Gguf::parse(&b.0).is_err()); + let mut b = B::new(0, 1); + b.s("k"); + b.0.extend(9u32.to_le_bytes()); + b.0.extend(4u32.to_le_bytes()); + b.0.extend(u64::MAX.to_le_bytes()); + assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::Overflow); + let mut b = B::new(0, 1); + b.s("k"); + b.0.extend(9u32.to_le_bytes()); + b.0.extend(8u32.to_le_bytes()); + b.0.extend((1u64 << 60).to_le_bytes()); + assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::TooMany); + let mut b = B::new(0, 1); + b.s("k"); + b.0.extend(9u32.to_le_bytes()); + b.0.extend(9u32.to_le_bytes()); + b.0.extend(1u64.to_le_bytes()); + assert!(Gguf::parse(&b.0).is_err()); + // Invalid UTF-8 key. + let mut b = B::new(0, 1); + b.0.extend(2u64.to_le_bytes()); + b.0.extend([0xff, 0xfe]); + b.0.extend(4u32.to_le_bytes()); + b.0.extend(0u32.to_le_bytes()); + assert_eq!(Gguf::parse(&b.0).unwrap_err(), GgufError::BadUtf8); +} + +#[test] +fn byte_flip_fuzz_never_panics() { + let f = good_small(); + let mut rng = Rng(0x1234_5678_9abc_def1); + for _ in 0..20_000 { + let mut g = f.clone(); + for _ in 0..1 + rng.next() % 3 { + let i = (rng.next() % g.len() as u64) as usize; + g[i] = rng.next() as u8; + } + if rng.next() % 4 == 0 { + let n = (rng.next() % g.len() as u64) as usize; + g.truncate(n); + } + if let Ok(p) = Gguf::parse(&g) { + // Accessors on whatever parsed must also be panic free. + for t in p.tensors() { + let _ = p.tensor_data(t); + } + for (_, v) in p.kvs() { + if let Value::Array(a) = v { + let _ = a.strings().count() + + a.u32s().count() + + a.i32s().count() + + a.f32s().count(); + } + } + let _ = p.llama_params(); + let _ = p.tokenizer(); + } + } +} + +#[test] +fn dequantize_rejects_bad_lengths_without_panic() { + let mut out = vec![0f32; 256]; + for n in [0usize, 1, 143, 145, 288] { + assert!(dequantize(GgmlType::Q4K, &vec![0u8; n], &mut out).is_err()); + } + assert!(dequantize(GgmlType::Q6K, &[0u8; 209], &mut out).is_err()); + let mut odd = vec![0f32; 100]; + assert!(dequantize(GgmlType::Q4K, &[0u8; 144], &mut odd).is_err()); +}