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/src/gguf.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 / src / gguf.rs` 654 lines ยท 21350 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 //! Bounded GGUF v3 reader over a byte slice. 17 //! 18 //! Layout (GGUF spec, little endian): magic `GGUF`, u32 version, u64 tensor 19 //! count, u64 key/value count, the key/value pairs, the tensor infos, padding 20 //! to `general.alignment` (default 32), then the tensor data. 21 22 use alloc::vec::Vec; 23 use core::fmt; 24 25 use crate::half::{bf16_to_f32, f16_to_f32}; 26 27 /// Everything that can go wrong while reading a GGUF file. 28 #[derive(Debug, Clone, PartialEq, Eq)] 29 pub enum GgufError { 30 /// A read ran past the end of the input at this byte offset. 31 Truncated(usize), 32 BadMagic, 33 UnsupportedVersion(u32), 34 /// A declared count cannot fit in the remaining bytes. 35 TooMany, 36 BadUtf8, 37 /// Unknown or unsupported key/value type code. 38 BadValueType(u32), 39 /// `general.alignment` is zero, not a power of two, or not a u32. 40 BadAlignment, 41 /// Arithmetic overflow while computing sizes or offsets. 42 Overflow, 43 /// Tensor type code this reader cannot size. 44 UnsupportedType(u32), 45 /// More than 4 dimensions or zero dimensions. 46 BadDims, 47 /// Tensor offset or byte range falls outside the data section, or its 48 /// offset is not a multiple of the alignment. 49 TensorOutOfRange, 50 /// Required key absent. 51 Missing(&'static str), 52 /// Key present with a different type than requested. 53 WrongType(&'static str), 54 } 55 56 impl fmt::Display for GgufError { 57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 58 write!(f, "{self:?}") 59 } 60 } 61 62 /// GGUF metadata value type codes. 63 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 64 pub enum ValueType { 65 U8, 66 I8, 67 U16, 68 I16, 69 U32, 70 I32, 71 F32, 72 Bool, 73 Str, 74 Array, 75 U64, 76 I64, 77 F64, 78 } 79 80 impl ValueType { 81 fn from_code(c: u32) -> Result { 82 Ok(match c { 83 0 => Self::U8, 84 1 => Self::I8, 85 2 => Self::U16, 86 3 => Self::I16, 87 4 => Self::U32, 88 5 => Self::I32, 89 6 => Self::F32, 90 7 => Self::Bool, 91 8 => Self::Str, 92 9 => Self::Array, 93 10 => Self::U64, 94 11 => Self::I64, 95 12 => Self::F64, 96 other => return Err(GgufError::BadValueType(other)), 97 }) 98 } 99 100 /// Byte size for fixed-size scalars, `None` for string/array. 101 fn fixed_size(self) -> Option { 102 match self { 103 Self::U8 | Self::I8 | Self::Bool => Some(1), 104 Self::U16 | Self::I16 => Some(2), 105 Self::U32 | Self::I32 | Self::F32 => Some(4), 106 Self::U64 | Self::I64 | Self::F64 => Some(8), 107 Self::Str | Self::Array => None, 108 } 109 } 110 } 111 112 /// A one-dimensional array of scalars or strings, validated at parse time. 113 #[derive(Debug, Clone, Copy)] 114 pub struct ArrayView<'a> { 115 pub elem: ValueType, 116 len: usize, 117 data: &'a [u8], 118 } 119 120 impl<'a> ArrayView<'a> { 121 /// Number of elements. 122 pub fn len(&self) -> usize { 123 self.len 124 } 125 pub fn is_empty(&self) -> bool { 126 self.len == 0 127 } 128 /// Iterate strings; empty unless the element type is string. 129 pub fn strings(&self) -> impl Iterator + 'a { 130 let mut cur = Cursor::new(self.data); 131 let n = if self.elem == ValueType::Str { 132 self.len 133 } else { 134 0 135 }; 136 (0..n).map_while(move |_| cur.str().ok()) 137 } 138 fn chunks(&self, want: &[ValueType], size: usize) -> impl Iterator + 'a { 139 let ok = want.contains(&self.elem); 140 let data = if ok { self.data } else { &[][..] }; 141 data.chunks_exact(size) 142 } 143 /// Iterate u32 elements (empty unless element type is u32). 144 pub fn u32s(&self) -> impl Iterator + 'a { 145 self.chunks(&[ValueType::U32], 4) 146 .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) 147 } 148 /// Iterate i32 elements (empty unless element type is i32). 149 pub fn i32s(&self) -> impl Iterator + 'a { 150 self.chunks(&[ValueType::I32], 4) 151 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])) 152 } 153 /// Iterate f32 elements (empty unless element type is f32). 154 pub fn f32s(&self) -> impl Iterator + 'a { 155 self.chunks(&[ValueType::F32], 4) 156 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) 157 } 158 } 159 160 /// A metadata value. 161 #[derive(Debug, Clone, Copy)] 162 pub enum Value<'a> { 163 U8(u8), 164 I8(i8), 165 U16(u16), 166 I16(i16), 167 U32(u32), 168 I32(i32), 169 F32(f32), 170 Bool(bool), 171 Str(&'a str), 172 Array(ArrayView<'a>), 173 U64(u64), 174 I64(i64), 175 F64(f64), 176 } 177 178 impl<'a> Value<'a> { 179 /// Any integer value that fits in u64 (non-negative). 180 pub fn as_u64(&self) -> Option { 181 match *self { 182 Value::U8(v) => Some(v as u64), 183 Value::U16(v) => Some(v as u64), 184 Value::U32(v) => Some(v as u64), 185 Value::U64(v) => Some(v), 186 Value::I8(v) => u64::try_from(v).ok(), 187 Value::I16(v) => u64::try_from(v).ok(), 188 Value::I32(v) => u64::try_from(v).ok(), 189 Value::I64(v) => u64::try_from(v).ok(), 190 _ => None, 191 } 192 } 193 pub fn as_f32(&self) -> Option { 194 match *self { 195 Value::F32(v) => Some(v), 196 Value::F64(v) => Some(v as f32), 197 _ => None, 198 } 199 } 200 pub fn as_str(&self) -> Option<&'a str> { 201 match *self { 202 Value::Str(s) => Some(s), 203 _ => None, 204 } 205 } 206 pub fn as_array(&self) -> Option> { 207 match *self { 208 Value::Array(a) => Some(a), 209 _ => None, 210 } 211 } 212 } 213 214 /// ggml tensor storage types. 215 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] 216 pub enum GgmlType { 217 F32, 218 F16, 219 Q4_0, 220 Q4_1, 221 Q5_0, 222 Q5_1, 223 Q8_0, 224 Q8_1, 225 Q2K, 226 Q3K, 227 Q4K, 228 Q5K, 229 Q6K, 230 Q8K, 231 I8, 232 I16, 233 I32, 234 I64, 235 F64, 236 BF16, 237 } 238 239 impl GgmlType { 240 pub fn from_code(c: u32) -> Result { 241 Ok(match c { 242 0 => Self::F32, 243 1 => Self::F16, 244 2 => Self::Q4_0, 245 3 => Self::Q4_1, 246 6 => Self::Q5_0, 247 7 => Self::Q5_1, 248 8 => Self::Q8_0, 249 9 => Self::Q8_1, 250 10 => Self::Q2K, 251 11 => Self::Q3K, 252 12 => Self::Q4K, 253 13 => Self::Q5K, 254 14 => Self::Q6K, 255 15 => Self::Q8K, 256 24 => Self::I8, 257 25 => Self::I16, 258 26 => Self::I32, 259 27 => Self::I64, 260 28 => Self::F64, 261 30 => Self::BF16, 262 other => return Err(GgufError::UnsupportedType(other)), 263 }) 264 } 265 266 /// (weights per block, bytes per block). 267 pub fn block(self) -> (usize, usize) { 268 match self { 269 Self::F32 | Self::I32 => (1, 4), 270 Self::F16 | Self::BF16 | Self::I16 => (1, 2), 271 Self::I8 => (1, 1), 272 Self::I64 | Self::F64 => (1, 8), 273 Self::Q4_0 => (32, 18), 274 Self::Q4_1 => (32, 20), 275 Self::Q5_0 => (32, 22), 276 Self::Q5_1 => (32, 24), 277 Self::Q8_0 => (32, 34), 278 Self::Q8_1 => (32, 36), 279 Self::Q2K => (256, 84), 280 Self::Q3K => (256, 110), 281 Self::Q4K => (256, 144), 282 Self::Q5K => (256, 176), 283 Self::Q6K => (256, 210), 284 Self::Q8K => (256, 292), 285 } 286 } 287 } 288 289 /// One entry of the tensor table. 290 #[derive(Debug, Clone)] 291 pub struct TensorInfo<'a> { 292 pub name: &'a str, 293 /// Dimensions, `dims[0]` is the contiguous (row) length. Only the first 294 /// `n_dims` are meaningful. 295 pub dims: [u64; 4], 296 pub n_dims: u32, 297 pub ty: GgmlType, 298 /// Offset from the start of the data section. 299 pub offset: u64, 300 /// Total weights. 301 pub n_elements: u64, 302 /// Total bytes, from the type's block math. 303 pub n_bytes: u64, 304 } 305 306 impl TensorInfo<'_> { 307 /// Bytes in one row (`dims[0]` weights). 308 pub fn row_bytes(&self) -> u64 { 309 let (bw, bb) = self.ty.block(); 310 self.dims[0] / bw as u64 * bb as u64 311 } 312 } 313 314 /// Bounds-checked little-endian reader. 315 struct Cursor<'a> { 316 b: &'a [u8], 317 pos: usize, 318 } 319 320 impl<'a> Cursor<'a> { 321 fn new(b: &'a [u8]) -> Self { 322 Self { b, pos: 0 } 323 } 324 fn remaining(&self) -> usize { 325 self.b.len() - self.pos 326 } 327 fn take(&mut self, n: usize) -> Result<&'a [u8], GgufError> { 328 if n > self.remaining() { 329 return Err(GgufError::Truncated(self.pos)); 330 } 331 let s = &self.b[self.pos..self.pos + n]; 332 self.pos += n; 333 Ok(s) 334 } 335 fn arr(&mut self) -> Result<[u8; N], GgufError> { 336 let s = self.take(N)?; 337 let mut a = [0u8; N]; 338 a.copy_from_slice(s); 339 Ok(a) 340 } 341 fn u8(&mut self) -> Result { 342 Ok(self.arr::<1>()?[0]) 343 } 344 fn u16(&mut self) -> Result { 345 Ok(u16::from_le_bytes(self.arr()?)) 346 } 347 fn u32(&mut self) -> Result { 348 Ok(u32::from_le_bytes(self.arr()?)) 349 } 350 fn u64(&mut self) -> Result { 351 Ok(u64::from_le_bytes(self.arr()?)) 352 } 353 fn len64(&mut self) -> Result { 354 usize::try_from(self.u64()?).map_err(|_| GgufError::Overflow) 355 } 356 fn str(&mut self) -> Result<&'a str, GgufError> { 357 let n = self.len64()?; 358 let s = self.take(n)?; 359 core::str::from_utf8(s).map_err(|_| GgufError::BadUtf8) 360 } 361 362 fn value(&mut self, ty: ValueType) -> Result, GgufError> { 363 Ok(match ty { 364 ValueType::U8 => Value::U8(self.u8()?), 365 ValueType::I8 => Value::I8(self.u8()? as i8), 366 ValueType::U16 => Value::U16(self.u16()?), 367 ValueType::I16 => Value::I16(self.u16()? as i16), 368 ValueType::U32 => Value::U32(self.u32()?), 369 ValueType::I32 => Value::I32(self.u32()? as i32), 370 ValueType::F32 => Value::F32(f32::from_bits(self.u32()?)), 371 ValueType::Bool => match self.u8()? { 372 0 => Value::Bool(false), 373 1 => Value::Bool(true), 374 other => return Err(GgufError::BadValueType(other as u32)), 375 }, 376 ValueType::Str => Value::Str(self.str()?), 377 ValueType::U64 => Value::U64(self.u64()?), 378 ValueType::I64 => Value::I64(self.u64()? as i64), 379 ValueType::F64 => Value::F64(f64::from_bits(self.u64()?)), 380 ValueType::Array => { 381 let elem = ValueType::from_code(self.u32()?)?; 382 let len = self.len64()?; 383 let start = self.pos; 384 match elem.fixed_size() { 385 Some(sz) => { 386 let total = len.checked_mul(sz).ok_or(GgufError::Overflow)?; 387 self.take(total)?; 388 } 389 None if elem == ValueType::Str => { 390 // Each string needs at least its 8-byte length. 391 if len > self.remaining() / 8 { 392 return Err(GgufError::TooMany); 393 } 394 for _ in 0..len { 395 self.str()?; 396 } 397 } 398 None => return Err(GgufError::BadValueType(9)), // nested arrays 399 } 400 Value::Array(ArrayView { 401 elem, 402 len, 403 data: &self.b[start..self.pos], 404 }) 405 } 406 }) 407 } 408 } 409 410 /// A parsed GGUF file borrowing the input bytes. 411 #[derive(Debug)] 412 pub struct Gguf<'a> { 413 bytes: &'a [u8], 414 pub version: u32, 415 kv: Vec<(&'a str, Value<'a>)>, 416 tensors: Vec>, 417 pub alignment: u64, 418 /// Byte offset of the tensor data section within the input. 419 pub data_start: usize, 420 } 421 422 impl<'a> Gguf<'a> { 423 /// Parse and fully validate the header, metadata and tensor table. 424 pub fn parse(bytes: &'a [u8]) -> Result { 425 let mut c = Cursor::new(bytes); 426 if c.take(4)? != b"GGUF" { 427 return Err(GgufError::BadMagic); 428 } 429 let version = c.u32()?; 430 if version != 3 { 431 return Err(GgufError::UnsupportedVersion(version)); 432 } 433 let n_tensors = c.len64()?; 434 let n_kv = c.len64()?; 435 // A kv needs >= 8 (key len) + 4 (type) bytes; a tensor info >= 8+4+8+4+8. 436 if n_kv > c.remaining() / 12 || n_tensors > c.remaining() / 32 { 437 return Err(GgufError::TooMany); 438 } 439 440 let mut kv = Vec::with_capacity(n_kv); 441 for _ in 0..n_kv { 442 let key = c.str()?; 443 let ty = ValueType::from_code(c.u32()?)?; 444 kv.push((key, c.value(ty)?)); 445 } 446 447 let alignment = match kv.iter().find(|(k, _)| *k == "general.alignment") { 448 None => 32, 449 Some((_, v)) => match *v { 450 Value::U32(a) if a != 0 && a.is_power_of_two() => a as u64, 451 _ => return Err(GgufError::BadAlignment), 452 }, 453 }; 454 455 let mut tensors: Vec> = Vec::with_capacity(n_tensors); 456 for _ in 0..n_tensors { 457 let name = c.str()?; 458 let n_dims = c.u32()?; 459 if n_dims == 0 || n_dims > 4 { 460 return Err(GgufError::BadDims); 461 } 462 let mut dims = [1u64; 4]; 463 for d in dims.iter_mut().take(n_dims as usize) { 464 *d = c.u64()?; 465 } 466 let ty = GgmlType::from_code(c.u32()?)?; 467 let offset = c.u64()?; 468 let mut n_elements: u64 = 1; 469 for d in dims { 470 n_elements = n_elements.checked_mul(d).ok_or(GgufError::Overflow)?; 471 } 472 let (bw, bb) = ty.block(); 473 if dims[0] % bw as u64 != 0 { 474 return Err(GgufError::BadDims); 475 } 476 let n_bytes = (n_elements / bw as u64) 477 .checked_mul(bb as u64) 478 .ok_or(GgufError::Overflow)?; 479 tensors.push(TensorInfo { 480 name, 481 dims, 482 n_dims, 483 ty, 484 offset, 485 n_elements, 486 n_bytes, 487 }); 488 } 489 490 let pos = c.pos as u64; 491 let data_start = 492 pos.checked_add(alignment - 1).ok_or(GgufError::Overflow)? & !(alignment - 1); 493 let data_start = usize::try_from(data_start).map_err(|_| GgufError::Overflow)?; 494 if data_start > bytes.len() { 495 return Err(GgufError::Truncated(bytes.len())); 496 } 497 let data_len = (bytes.len() - data_start) as u64; 498 for t in &tensors { 499 let end = t.offset.checked_add(t.n_bytes).ok_or(GgufError::Overflow)?; 500 if end > data_len || t.offset % alignment != 0 { 501 return Err(GgufError::TensorOutOfRange); 502 } 503 } 504 505 Ok(Self { 506 bytes, 507 version, 508 kv, 509 tensors, 510 alignment, 511 data_start, 512 }) 513 } 514 515 /// All key/value pairs in file order. 516 pub fn kvs(&self) -> &[(&'a str, Value<'a>)] { 517 &self.kv 518 } 519 /// Look up a metadata value. 520 pub fn get(&self, key: &str) -> Option> { 521 self.kv.iter().find(|(k, _)| *k == key).map(|(_, v)| *v) 522 } 523 /// All tensor infos in file order. 524 pub fn tensors(&self) -> &[TensorInfo<'a>] { 525 &self.tensors 526 } 527 /// Find a tensor by name. 528 pub fn tensor(&self, name: &str) -> Option<&TensorInfo<'a>> { 529 self.tensors.iter().find(|t| t.name == name) 530 } 531 /// Raw bytes of a tensor (range validated at parse time). 532 pub fn tensor_data(&self, t: &TensorInfo<'_>) -> &'a [u8] { 533 let s = self.data_start + t.offset as usize; 534 &self.bytes[s..s + t.n_bytes as usize] 535 } 536 537 fn req(&self, key: &'static str) -> Result, GgufError> { 538 self.get(key).ok_or(GgufError::Missing(key)) 539 } 540 /// Required unsigned integer key. 541 pub fn u64_key(&self, key: &'static str) -> Result { 542 self.req(key)?.as_u64().ok_or(GgufError::WrongType(key)) 543 } 544 /// Required key that must fit in u32. 545 pub fn u32_key(&self, key: &'static str) -> Result { 546 u32::try_from(self.u64_key(key)?).map_err(|_| GgufError::WrongType(key)) 547 } 548 pub fn f32_key(&self, key: &'static str) -> Result { 549 self.req(key)?.as_f32().ok_or(GgufError::WrongType(key)) 550 } 551 pub fn str_key(&self, key: &'static str) -> Result<&'a str, GgufError> { 552 self.req(key)?.as_str().ok_or(GgufError::WrongType(key)) 553 } 554 pub fn array_key(&self, key: &'static str) -> Result, GgufError> { 555 self.req(key)?.as_array().ok_or(GgufError::WrongType(key)) 556 } 557 558 /// `general.architecture` (for Llama-3.2 this is `llama`). 559 pub fn architecture(&self) -> Result<&'a str, GgufError> { 560 self.str_key("general.architecture") 561 } 562 563 /// Hyperparameters, read from `.` keys as written by llama.cpp. 564 pub fn llama_params(&self) -> Result { 565 if self.architecture()? != "llama" { 566 return Err(GgufError::WrongType("general.architecture")); 567 } 568 let vocab_size = match self.get("llama.vocab_size") { 569 Some(v) => v 570 .as_u64() 571 .and_then(|v| u32::try_from(v).ok()) 572 .ok_or(GgufError::WrongType("llama.vocab_size"))?, 573 // Not stored by llama.cpp converters; derive from the token list. 574 None => u32::try_from(self.array_key("tokenizer.ggml.tokens")?.len()) 575 .map_err(|_| GgufError::Overflow)?, 576 }; 577 Ok(LlamaParams { 578 block_count: self.u32_key("llama.block_count")?, 579 embedding_length: self.u32_key("llama.embedding_length")?, 580 head_count: self.u32_key("llama.attention.head_count")?, 581 head_count_kv: self.u32_key("llama.attention.head_count_kv")?, 582 feed_forward_length: self.u32_key("llama.feed_forward_length")?, 583 context_length: self.u32_key("llama.context_length")?, 584 rope_freq_base: self.f32_key("llama.rope.freq_base")?, 585 rms_norm_eps: self.f32_key("llama.attention.layer_norm_rms_epsilon")?, 586 vocab_size, 587 }) 588 } 589 590 /// Token strings, scores and types plus special ids. 591 pub fn tokenizer(&self) -> Result, GgufError> { 592 let tokens = self.array_key("tokenizer.ggml.tokens")?; 593 let scores = self.array_key("tokenizer.ggml.scores").ok(); 594 let token_type = self.array_key("tokenizer.ggml.token_type").ok(); 595 let merges = self.array_key("tokenizer.ggml.merges").ok(); 596 Ok(TokenizerData { 597 tokens, 598 scores, 599 token_type, 600 merges, 601 bos_id: self.u32_key("tokenizer.ggml.bos_token_id").ok(), 602 eos_id: self.u32_key("tokenizer.ggml.eos_token_id").ok(), 603 }) 604 } 605 } 606 607 /// Model hyperparameters needed by the Llama graph. 608 #[derive(Debug, Clone, Copy, PartialEq)] 609 pub struct LlamaParams { 610 pub block_count: u32, 611 pub embedding_length: u32, 612 pub head_count: u32, 613 pub head_count_kv: u32, 614 pub feed_forward_length: u32, 615 pub context_length: u32, 616 pub rope_freq_base: f32, 617 pub rms_norm_eps: f32, 618 pub vocab_size: u32, 619 } 620 621 /// Tokenizer arrays as stored in the file. 622 #[derive(Debug, Clone, Copy)] 623 pub struct TokenizerData<'a> { 624 pub tokens: ArrayView<'a>, 625 pub scores: Option>, 626 pub token_type: Option>, 627 pub merges: Option>, 628 pub bos_id: Option, 629 pub eos_id: Option, 630 } 631 632 /// Dequantize any row-contiguous slice of a tensor of the plain float types 633 /// into `out`; quantized types go through [`crate::quant::dequantize`]. 634 pub(crate) fn plain_to_f32(ty: GgmlType, src: &[u8], out: &mut [f32]) -> bool { 635 match ty { 636 GgmlType::F32 => { 637 for (o, c) in out.iter_mut().zip(src.chunks_exact(4)) { 638 *o = f32::from_le_bytes([c[0], c[1], c[2], c[3]]); 639 } 640 } 641 GgmlType::F16 => { 642 for (o, c) in out.iter_mut().zip(src.chunks_exact(2)) { 643 *o = f16_to_f32(u16::from_le_bytes([c[0], c[1]])); 644 } 645 } 646 GgmlType::BF16 => { 647 for (o, c) in out.iter_mut().zip(src.chunks_exact(2)) { 648 *o = bf16_to_f32(u16::from_le_bytes([c[0], c[1]])); 649 } 650 } 651 _ => return false, 652 } 653 true 654 }