Skip to main content

engram_parser/gguf/
layout.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Parsed GGUF file layout: metadata KV store + tensor directory.
4//!
5//! This module is file-agnostic: it operates on an already-loaded
6//! `&[u8]` slice (typically the full contents of a `.gguf` file). It
7//! does **not** perform any neural-network math — only header parsing,
8//! bounds-checked tensor-directory extraction, and metadata coercion.
9
10use std::collections::HashMap;
11
12use super::cursor::{
13    GGUF_MAGIC, GGUF_VERSION, GgufCursor, invalid_layout, is_signed_layout_type, unsupported,
14};
15use super::limits::{ParseLimits, align_up_checked, u64_to_usize};
16use super::tensor::{DType, Tensor};
17use crate::error::{HostSizeField, ParseLimitKind, ParserError, Result};
18
19/// Parsed GGUF metadata key-value store.
20///
21/// GGUF stores arbitrary scalar KV pairs. We keep strings and numeric
22/// values in typed maps; signed integers are additionally kept in
23/// `signed_numerics` so callers can distinguish bit-preserved negatives
24/// from large unsigned `UINT64` values. Array values are skipped (their
25/// byte contents remain available via the original file buffer if needed).
26#[derive(Debug, Clone, Default)]
27pub struct GgufMetadata {
28    /// String-typed KV pairs (e.g. `general.architecture = "olmoe"`).
29    pub strings: HashMap<String, String>,
30    /// Numeric-typed KV pairs coerced to `u64`
31    /// (e.g. `olmoe.expert_count = 64`).
32    pub numerics: HashMap<String, u64>,
33    /// Signed integer KV pairs coerced to `i64`, keyed separately so
34    /// `numeric()` can reject negatives without rejecting large unsigned
35    /// `UINT64` metadata.
36    pub(crate) signed_numerics: HashMap<String, i64>,
37    /// `f32`-typed KV pairs.
38    pub floats_32: HashMap<String, f32>,
39    /// `f64`-typed KV pairs.
40    pub floats_64: HashMap<String, f64>,
41}
42
43impl GgufMetadata {
44    /// Convenience: architecture string (`general.architecture`) or `"unknown"`.
45    pub fn architecture(&self) -> &str {
46        self.strings
47            .get("general.architecture")
48            .map(String::as_str)
49            .unwrap_or("unknown")
50    }
51
52    /// Convenience: numeric KV coerced to `usize`.
53    ///
54    /// Signed integer KVs are checked first: a negative value returns
55    /// `None`. Unsigned `UINT64` values larger than `i64::MAX` are still
56    /// accepted as long as they fit in `usize`.
57    pub fn numeric(&self, key: &str) -> Option<usize> {
58        if let Some(&s) = self.signed_numerics.get(key) {
59            return usize::try_from(s).ok();
60        }
61        let &v = self.numerics.get(key)?;
62        usize::try_from(v).ok()
63    }
64
65    /// Convenience: quantization label.
66    ///
67    /// Prefers the string KV `general.quantization_type`. When that is
68    /// missing, falls back to the **current** `general.file_type` numeric
69    /// (GGUF enum): `0 → "F32"`, `1 → "F16"`, otherwise `"GGUF(n)"`.
70    /// Returns `"unknown"` when neither is present. Derived at call time
71    /// so `Default` + public map edits stay consistent.
72    pub fn quantization(&self) -> String {
73        if let Some(s) = self.strings.get("general.quantization_type") {
74            return s.clone();
75        }
76        // If a signed value was stored, reject negatives rather than
77        // rendering them as huge unsigned labels.
78        if let Some(&s) = self.signed_numerics.get("general.file_type") {
79            return match s {
80                0 => "F32".into(),
81                1 => "F16".into(),
82                n if n >= 0 => format!("GGUF({n})"),
83                _ => "unknown".into(),
84            };
85        }
86        match self.numerics.get("general.file_type").copied() {
87            Some(0) => "F32".into(),
88            Some(1) => "F16".into(),
89            Some(n) => format!("GGUF({n})"),
90            None => "unknown".into(),
91        }
92    }
93
94    /// Convenience: numeric KV coerced to `usize`, looking up
95    /// `{architecture}.{key}` (e.g. `olmoe.block_count`).
96    ///
97    /// Returns `None` if the architecture is unknown or the key is missing.
98    pub fn arch_numeric(&self, key: &str) -> Option<usize> {
99        let arch = self.architecture();
100        if arch == "unknown" {
101            return None;
102        }
103        let full_key = format!("{arch}.{key}");
104        self.numeric(&full_key)
105    }
106
107    /// Convenience: block count from `{architecture}.block_count`.
108    pub fn block_count(&self) -> Option<usize> {
109        self.arch_numeric("block_count")
110    }
111
112    /// Convenience: expert count from `{architecture}.expert_count`
113    /// (some models use `num_experts` instead).
114    pub fn expert_count(&self) -> Option<usize> {
115        self.arch_numeric("expert_count")
116            .or_else(|| self.arch_numeric("num_experts"))
117    }
118
119    /// Convenience: number of experts used per token from
120    /// `{architecture}.expert_used_count` (some models use
121    /// `num_experts_per_tok`).
122    pub fn expert_used_count(&self) -> Option<usize> {
123        self.arch_numeric("expert_used_count")
124            .or_else(|| self.arch_numeric("num_experts_per_tok"))
125    }
126
127    /// Convenience: embedding length from `{architecture}.embedding_length`.
128    pub fn embedding_length(&self) -> Option<usize> {
129        self.arch_numeric("embedding_length")
130    }
131
132    /// Convenience: attention head count from
133    /// `{architecture}.attention.head_count`.
134    pub fn head_count(&self) -> Option<usize> {
135        self.arch_numeric("attention.head_count")
136    }
137
138    /// Generic string metadata lookup.
139    pub fn string(&self, key: &str) -> Option<&str> {
140        self.strings.get(key).map(String::as_str)
141    }
142
143    /// Generic f32 metadata lookup.
144    pub fn float32(&self, key: &str) -> Option<f32> {
145        self.floats_32.get(key).copied()
146    }
147
148    /// Generic f64 metadata lookup.
149    pub fn float64(&self, key: &str) -> Option<f64> {
150        self.floats_64.get(key).copied()
151    }
152}
153
154/// Fully-parsed GGUF checkpoint layout.
155///
156/// Owns the raw file bytes (loaded into a `Vec<u8>` by [`load_gguf`])
157/// and all derived tensor directory + metadata information. Callers use
158/// the [`Tensor`] handles + [`GgufLayout::tensor_bytes`] to obtain raw
159/// byte slices for each weight.
160///
161/// [`load_gguf`]: super::load_gguf
162#[derive(Debug)]
163pub struct GgufLayout {
164    /// Path the checkpoint was loaded from (kept for error messages).
165    pub path: String,
166    /// Parsed KV metadata.
167    pub metadata: GgufMetadata,
168    /// Name -> tensor directory entry.
169    pub tensors: HashMap<String, Tensor>,
170    /// Byte alignment specified by the file (default 32).
171    pub alignment: usize,
172    /// Absolute byte offset within `bytes` where tensor payloads begin.
173    pub tensor_data_offset: usize,
174    /// Full file contents. Tensor payloads live at `bytes[tensor.absolute_offset ..]`.
175    pub bytes: Vec<u8>,
176}
177
178impl GgufLayout {
179    /// Return a borrowed slice of the raw tensor payload bytes.
180    pub fn tensor_bytes<'a>(&'a self, tensor: &Tensor) -> Result<&'a [u8]> {
181        tensor_payload_bytes(&self.bytes, &self.path, tensor)
182    }
183
184    /// Lookup a tensor by exact name.
185    pub fn tensor(&self, name: &str) -> Result<&Tensor> {
186        self.tensors
187            .get(name)
188            .ok_or_else(|| ParserError::MissingTensor {
189                name: name.to_owned(),
190                path: self.path.clone(),
191            })
192    }
193
194    /// Find all tensors whose name ends with the given suffix. Useful
195    /// for locating per-block MoE tensors like `ffn_gate_exps.weight`.
196    pub fn find_tensors_with_suffix<'a>(&'a self, suffix: &str) -> Vec<&'a Tensor> {
197        let mut matches: Vec<&Tensor> = self
198            .tensors
199            .values()
200            .filter(|t| t.name.ends_with(suffix))
201            .collect();
202        matches.sort_unstable_by_key(|t| tensor_block_sort_key(&t.name));
203        matches
204    }
205}
206
207/// Bounds-checked tensor payload slice from any byte source (owned buffer or mmap).
208pub(crate) fn tensor_payload_bytes<'a>(
209    bytes: &'a [u8],
210    path: &str,
211    tensor: &Tensor,
212) -> Result<&'a [u8]> {
213    let start = tensor.absolute_offset;
214    let end = start.checked_add(tensor.byte_len).ok_or_else(|| {
215        invalid_layout(
216            path,
217            format!("tensor '{}' byte-length overflow", tensor.name),
218        )
219    })?;
220    if end > bytes.len() {
221        return Err(invalid_layout(
222            path,
223            format!(
224                "tensor '{}' extends beyond mapped file ({end} > {})",
225                tensor.name,
226                bytes.len()
227            ),
228        ));
229    }
230    Ok(&bytes[start..end])
231}
232
233struct LayoutHeader {
234    tensor_count: usize,
235    kv_count: usize,
236}
237
238/// Parse the GGUF header + KV metadata + tensor directory out of a
239/// byte slice. Does not validate payload bytes, only directory offsets.
240pub(crate) fn parse_layout(
241    bytes: &[u8],
242    path: &str,
243    limits: ParseLimits,
244) -> Result<(GgufMetadata, HashMap<String, Tensor>, usize, usize)> {
245    let mut cursor = GgufCursor::with_limits(bytes, path, limits);
246    let header = read_layout_header(&mut cursor, path)?;
247    let (alignment, metadata) = read_metadata_section(&mut cursor, path, header.kv_count)?;
248    let mut tensors = read_tensor_directory(&mut cursor, path, header.tensor_count)?;
249    let tensor_data_offset =
250        finalize_tensor_offsets(&mut tensors, cursor.offset(), alignment, bytes.len(), path)?;
251    Ok((metadata, tensors, alignment, tensor_data_offset))
252}
253
254fn read_layout_header(cursor: &mut GgufCursor<'_>, path: &str) -> Result<LayoutHeader> {
255    validate_gguf_header(cursor, path)?;
256    let limits = cursor.limits();
257    let tensor_count = limits.bounded_usize(
258        path,
259        ParseLimitKind::TensorCount,
260        HostSizeField::TensorCount,
261        cursor.read_u64()?,
262    )?;
263    let kv_count = limits.bounded_usize(
264        path,
265        ParseLimitKind::KvCount,
266        HostSizeField::KvCount,
267        cursor.read_u64()?,
268    )?;
269    Ok(LayoutHeader {
270        tensor_count,
271        kv_count,
272    })
273}
274
275fn validate_gguf_header(cursor: &mut GgufCursor<'_>, path: &str) -> Result<()> {
276    let magic = cursor.read_exact(4)?;
277    if magic != GGUF_MAGIC {
278        return Err(unsupported(
279            path,
280            format!("unrecognised GGUF magic bytes: {magic:?}"),
281        ));
282    }
283
284    let version = cursor.read_u32()?;
285    if version != GGUF_VERSION {
286        return Err(unsupported(
287            path,
288            format!("unsupported GGUF version {version}; expected {GGUF_VERSION}"),
289        ));
290    }
291
292    Ok(())
293}
294
295fn read_metadata_section(
296    cursor: &mut GgufCursor<'_>,
297    path: &str,
298    kv_count: usize,
299) -> Result<(usize, GgufMetadata)> {
300    let mut alignment: usize = 32;
301    let mut metadata = GgufMetadata::default();
302    cursor.begin_metadata_section();
303
304    for _ in 0..kv_count {
305        let key = cursor.read_string()?;
306        let value_type = cursor.read_u32()?;
307        if key == "general.alignment" {
308            // Layout-critical: reject signed negatives (do not wrap to huge usize)
309            // and require a positive power of two.
310            alignment = cursor.read_nonneg_layout_usize(value_type)?;
311            if alignment == 0 || !alignment.is_power_of_two() {
312                return Err(invalid_layout(
313                    path,
314                    format!("general.alignment must be a positive power of 2, got {alignment}"),
315                ));
316            }
317        } else {
318            capture_kv(cursor, &mut metadata, key, value_type)?;
319        }
320    }
321
322    cursor.end_metadata_section();
323    Ok((alignment, metadata))
324}
325
326fn read_tensor_directory(
327    cursor: &mut GgufCursor<'_>,
328    path: &str,
329    tensor_count: usize,
330) -> Result<HashMap<String, Tensor>> {
331    let mut tensors = HashMap::with_capacity(tensor_count);
332    for _ in 0..tensor_count {
333        let tensor = read_tensor_entry(cursor, path)?;
334        // A HashMap cannot report a duplicate after `insert` (it silently
335        // last-wins), so reject the collision before inserting.
336        if tensors.contains_key(&tensor.name) {
337            return Err(invalid_layout(
338                path,
339                format!("duplicate tensor name '{}' in directory", tensor.name),
340            ));
341        }
342        tensors.insert(tensor.name.clone(), tensor);
343    }
344    Ok(tensors)
345}
346
347fn read_tensor_entry(cursor: &mut GgufCursor<'_>, path: &str) -> Result<Tensor> {
348    let name = cursor.read_string()?;
349    let dims = read_tensor_dims(cursor, path, &name)?;
350    let ggml_type = cursor.read_u32()?;
351    let relative_offset = u64_to_usize(cursor.read_u64()?, HostSizeField::RelativeOffset, path)?;
352    let dtype = DType::from_ggml_type(ggml_type);
353    let n_elements = tensor_element_count(&dims, &name, path)?;
354    validate_blocked_inner_dim(dtype, &dims, &name, path)?;
355    let byte_len = tensor_byte_len(dtype, ggml_type, n_elements, &name, path)?;
356
357    Ok(Tensor {
358        name,
359        dims,
360        dtype,
361        ggml_type,
362        n_elements,
363        byte_len,
364        relative_offset,
365        absolute_offset: 0,
366    })
367}
368
369/// Blocked quant layouts pack along the **innermost** GGUF dim (`dims[0]`).
370/// Total element count alone can accept shapes that cannot form valid blocks
371/// per row (e.g. Q4_0 with dims `[16, 2]` → 32 elems but row len 16).
372fn validate_blocked_inner_dim(dtype: DType, dims: &[usize], name: &str, path: &str) -> Result<()> {
373    let Some(block) = dtype.quant_block_size() else {
374        return Ok(());
375    };
376    let Some(&inner) = dims.first() else {
377        return Ok(());
378    };
379    if inner.is_multiple_of(block) {
380        return Ok(());
381    }
382    Err(invalid_layout(
383        path,
384        format!(
385            "tensor '{name}' innermost dim {inner} is not divisible by \
386             quant block size {block} for dtype {}",
387            dtype.label()
388        ),
389    ))
390}
391
392fn read_tensor_dims(cursor: &mut GgufCursor<'_>, path: &str, _name: &str) -> Result<Vec<usize>> {
393    let n_dims_raw = u64::from(cursor.read_u32()?);
394    let n_dims = cursor.limits().bounded_usize(
395        path,
396        ParseLimitKind::TensorRank,
397        HostSizeField::TensorRank,
398        n_dims_raw,
399    )?;
400
401    let mut dims = Vec::with_capacity(n_dims);
402    for _ in 0..n_dims {
403        dims.push(u64_to_usize(
404            cursor.read_u64()?,
405            HostSizeField::TensorDim,
406            path,
407        )?);
408    }
409    Ok(dims)
410}
411
412fn tensor_element_count(dims: &[usize], name: &str, path: &str) -> Result<usize> {
413    dims.iter()
414        .try_fold(1usize, |acc, &d| acc.checked_mul(d))
415        .ok_or_else(|| invalid_layout(path, format!("tensor '{name}' element count overflow")))
416}
417
418fn tensor_byte_len(
419    dtype: DType,
420    ggml_type: u32,
421    n_elements: usize,
422    name: &str,
423    path: &str,
424) -> Result<usize> {
425    dtype.byte_len_for_elements(n_elements).ok_or_else(|| {
426        invalid_layout(
427            path,
428            format!(
429                "tensor '{name}' (ggml_type={ggml_type}) has unknown byte-length for {n_elements} elements",
430            ),
431        )
432    })
433}
434
435/// Resolve each tensor's absolute offset and enforce the tensor-directory
436/// packing contract.
437///
438/// Every tensor payload range `[absolute_offset, absolute_offset + byte_len)`
439/// must lie fully within the file/mapping (`total_len`) and must not overlap
440/// any other tensor's range. Gaps between consecutive ranges are permitted
441/// (they are normal alignment padding), so contiguity is not required.
442/// Zero-length tensors (`byte_len == 0`) occupy no bytes: their
443/// `absolute_offset` is still range-checked against `total_len`, but they are
444/// excluded from the overlap comparison because an empty range cannot overlap.
445///
446/// This is the semantic directory contract (duplicate names are rejected
447/// earlier in [`read_tensor_directory`]). The RM-1358 offset-wrap guard
448/// (`tensor_data_offset + relative_offset` via `checked_add`) is a separate,
449/// preserved concern.
450fn finalize_tensor_offsets(
451    tensors: &mut HashMap<String, Tensor>,
452    cursor_offset: usize,
453    alignment: usize,
454    total_len: usize,
455    path: &str,
456) -> Result<usize> {
457    let tensor_data_offset = align_up_checked(cursor_offset, alignment, path)?;
458    for tensor in tensors.values_mut() {
459        tensor.absolute_offset = tensor_data_offset
460            .checked_add(tensor.relative_offset)
461            .ok_or_else(|| {
462                invalid_layout(
463                    path,
464                    format!("tensor '{}' absolute offset overflow", tensor.name),
465                )
466            })?;
467        let end = tensor
468            .absolute_offset
469            .checked_add(tensor.byte_len)
470            .ok_or_else(|| {
471                invalid_layout(
472                    path,
473                    format!("tensor '{}' byte-length overflow", tensor.name),
474                )
475            })?;
476        if end > total_len {
477            return Err(invalid_layout(
478                path,
479                format!(
480                    "tensor '{}' extends beyond file ({end} > {total_len})",
481                    tensor.name
482                ),
483            ));
484        }
485    }
486    check_no_overlap(tensors, path)?;
487    Ok(tensor_data_offset)
488}
489
490/// Reject overlapping tensor payload ranges. Zero-length tensors are skipped
491/// (an empty range cannot overlap). Gaps between ranges are allowed.
492fn check_no_overlap(tensors: &HashMap<String, Tensor>, path: &str) -> Result<()> {
493    let mut ranges: Vec<(&str, usize, usize)> = tensors
494        .values()
495        .filter(|t| t.byte_len > 0)
496        .map(|t| (t.name.as_str(), t.absolute_offset, t.byte_len))
497        .collect();
498    // Sort by start offset, tie-break by name for deterministic messages.
499    ranges.sort_unstable_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(b.0)));
500    for window in ranges.windows(2) {
501        let (prev_name, prev_start, prev_len) = window[0];
502        let (name, start, _) = window[1];
503        // Ranges are sorted by start; `prev_start + prev_len` cannot overflow
504        // because both are already bounded by `total_len`.
505        if start < prev_start + prev_len {
506            return Err(invalid_layout(
507                path,
508                format!("tensors '{prev_name}' and '{name}' have overlapping payloads"),
509            ));
510        }
511    }
512    Ok(())
513}
514
515fn capture_kv(
516    cursor: &mut GgufCursor<'_>,
517    metadata: &mut GgufMetadata,
518    key: String,
519    value_type: u32,
520) -> Result<()> {
521    use super::cursor::{
522        GGUF_VALUE_TYPE_BOOL, GGUF_VALUE_TYPE_FLOAT32, GGUF_VALUE_TYPE_FLOAT64,
523        GGUF_VALUE_TYPE_INT8, GGUF_VALUE_TYPE_INT16, GGUF_VALUE_TYPE_INT32, GGUF_VALUE_TYPE_INT64,
524        GGUF_VALUE_TYPE_STRING, GGUF_VALUE_TYPE_UINT8, GGUF_VALUE_TYPE_UINT16,
525        GGUF_VALUE_TYPE_UINT32, GGUF_VALUE_TYPE_UINT64,
526    };
527    match value_type {
528        GGUF_VALUE_TYPE_UINT8
529        | GGUF_VALUE_TYPE_INT8
530        | GGUF_VALUE_TYPE_UINT16
531        | GGUF_VALUE_TYPE_INT16
532        | GGUF_VALUE_TYPE_UINT32
533        | GGUF_VALUE_TYPE_INT32
534        | GGUF_VALUE_TYPE_UINT64
535        | GGUF_VALUE_TYPE_INT64
536        | GGUF_VALUE_TYPE_BOOL => capture_numeric_kv(cursor, metadata, key, value_type),
537        GGUF_VALUE_TYPE_FLOAT32 => capture_f32_kv(cursor, metadata, key),
538        GGUF_VALUE_TYPE_FLOAT64 => capture_f64_kv(cursor, metadata, key),
539        GGUF_VALUE_TYPE_STRING => capture_string_kv(cursor, metadata, key),
540        _ => capture_skipped_kv(cursor, value_type),
541    }
542}
543
544fn capture_numeric_kv(
545    cursor: &mut GgufCursor<'_>,
546    metadata: &mut GgufMetadata,
547    key: String,
548    value_type: u32,
549) -> Result<()> {
550    let v = cursor.read_numeric_as_u64(value_type)?;
551    if is_signed_layout_type(value_type) {
552        metadata.signed_numerics.insert(key.clone(), v as i64);
553    }
554    metadata.numerics.insert(key, v);
555    Ok(())
556}
557
558fn capture_f32_kv(
559    cursor: &mut GgufCursor<'_>,
560    metadata: &mut GgufMetadata,
561    key: String,
562) -> Result<()> {
563    let v = cursor.read_f32()?;
564    metadata.floats_32.insert(key, v);
565    Ok(())
566}
567
568fn capture_f64_kv(
569    cursor: &mut GgufCursor<'_>,
570    metadata: &mut GgufMetadata,
571    key: String,
572) -> Result<()> {
573    let v = cursor.read_f64()?;
574    metadata.floats_64.insert(key, v);
575    Ok(())
576}
577
578fn capture_string_kv(
579    cursor: &mut GgufCursor<'_>,
580    metadata: &mut GgufMetadata,
581    key: String,
582) -> Result<()> {
583    let v = cursor.read_string()?;
584    metadata.strings.insert(key, v);
585    Ok(())
586}
587
588fn capture_skipped_kv(cursor: &mut GgufCursor<'_>, value_type: u32) -> Result<()> {
589    cursor.skip_value(value_type)
590}
591
592fn tensor_block_sort_key(name: &str) -> (usize, String) {
593    let block = name
594        .strip_prefix("blk.")
595        .and_then(|rest| rest.split_once('.'))
596        .and_then(|(idx, _)| idx.parse::<usize>().ok())
597        .unwrap_or(usize::MAX);
598    (block, name.to_owned())
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604
605    #[test]
606    fn numeric_keeps_large_unsigned_and_rejects_negative_signed() {
607        let mut meta = GgufMetadata::default();
608
609        // A UINT64 larger than i64::MAX is still accepted when it fits in usize.
610        meta.numerics.insert("big".into(), u64::MAX);
611        #[cfg(target_pointer_width = "64")]
612        assert_eq!(meta.numeric("big"), Some(usize::MAX));
613
614        // A signed negative value must not wrap into a positive usize.
615        meta.numerics.insert("neg".into(), (-7i64) as u64);
616        meta.signed_numerics.insert("neg".into(), -7);
617        assert_eq!(meta.numeric("neg"), None);
618    }
619
620    #[test]
621    fn quantization_suppresses_negative_signed_file_type() {
622        let mut meta = GgufMetadata::default();
623
624        // A negative signed file_type must not render as an unsigned label.
625        meta.numerics
626            .insert("general.file_type".into(), (-7i64) as u64);
627        meta.signed_numerics.insert("general.file_type".into(), -7);
628        assert_eq!(meta.quantization(), "unknown");
629
630        // A positive signed file_type still resolves normally.
631        meta.signed_numerics.insert("general.file_type".into(), 15);
632        assert_eq!(meta.quantization(), "GGUF(15)");
633
634        // An unsigned file_type falls back to the unsigned map.
635        meta.signed_numerics.remove("general.file_type");
636        meta.numerics.insert("general.file_type".into(), 15);
637        assert_eq!(meta.quantization(), "GGUF(15)");
638    }
639}