Skip to main content

engram_parser/checkpoint/
gguf.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! GGUF backends for [`Checkpoint`], built on [`crate::gguf`].
3//!
4//! The wrappers own the format-specific layout plus a precomputed
5//! [`Catalog`]. [`crate::GgufLayout`] itself is unchanged; `layout()` /
6//! `into_layout()` keep MoE helpers, suffix search, dequant, and (with
7//! `mmap`) page-aligned views reachable.
8
9use std::borrow::Cow;
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use super::{
14    Catalog, Checkpoint, CheckpointFormat, CheckpointMetadata, CheckpointSource, MetadataValue,
15    SourceKind, TensorDType, TensorInfo, TensorLocation, TensorShape, delegate_catalog,
16};
17use crate::error::Result;
18use crate::gguf::{
19    DType, GgufLayout, GgufMetadata, ParseLimits, Tensor, ggml_type_label, load_gguf_with_limits,
20    parse_bytes_with_limits,
21};
22
23/// [`Checkpoint`] over an owned [`GgufLayout`] (whole file in memory).
24#[derive(Debug)]
25pub struct GgufBackend {
26    layout: GgufLayout,
27    catalog: Catalog,
28}
29
30impl GgufBackend {
31    /// Read and parse a `.gguf` file with [`ParseLimits::default`].
32    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
33        Self::open_with_limits(path, ParseLimits::default())
34    }
35
36    /// Read and parse a `.gguf` file with explicit limits.
37    pub fn open_with_limits(path: impl AsRef<Path>, limits: ParseLimits) -> Result<Self> {
38        let layout = load_gguf_with_limits(path, limits)?;
39        Ok(Self::with_kind(layout, SourceKind::SingleFile))
40    }
41
42    /// Parse an in-memory GGUF buffer. `label` is used as the source path.
43    pub fn from_bytes(bytes: Vec<u8>, label: impl Into<String>) -> Result<Self> {
44        let layout = parse_bytes_with_limits(bytes, label.into(), ParseLimits::default())?;
45        Ok(Self::with_kind(layout, SourceKind::InMemory))
46    }
47
48    /// Wrap an already-parsed layout. The source kind is
49    /// [`SourceKind::SingleFile`] when `layout.path` names an existing
50    /// file, otherwise [`SourceKind::InMemory`].
51    pub fn from_layout(layout: GgufLayout) -> Self {
52        let kind = if Path::new(&layout.path).is_file() {
53            SourceKind::SingleFile
54        } else {
55            SourceKind::InMemory
56        };
57        Self::with_kind(layout, kind)
58    }
59
60    fn with_kind(layout: GgufLayout, kind: SourceKind) -> Self {
61        let catalog = build_catalog(&layout.path, kind, &layout.metadata, &layout.tensors);
62        Self { layout, catalog }
63    }
64
65    /// Format-specific layout (MoE helpers, suffix search, dequant).
66    pub fn layout(&self) -> &GgufLayout {
67        &self.layout
68    }
69
70    /// Unwrap into the format-specific layout.
71    pub fn into_layout(self) -> GgufLayout {
72        self.layout
73    }
74}
75
76impl Checkpoint for GgufBackend {
77    delegate_catalog!();
78
79    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>> {
80        let info = self.catalog.require(name)?;
81        let bytes = self.layout.tensor_bytes(self.layout.tensor(name)?)?;
82        self.catalog.check_len(info, bytes.len())?;
83        Ok(Cow::Borrowed(bytes))
84    }
85}
86
87/// [`Checkpoint`] over a memory-mapped [`crate::GgufLayoutMmap`].
88///
89/// Callers must not truncate the file while the backend is alive
90/// (standard mmap invariant).
91#[cfg(feature = "mmap")]
92#[derive(Debug)]
93pub struct GgufMmapBackend {
94    layout: crate::gguf::GgufLayoutMmap,
95    catalog: Catalog,
96}
97
98#[cfg(feature = "mmap")]
99impl GgufMmapBackend {
100    /// Map and parse a `.gguf` file with [`ParseLimits::default`].
101    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
102        Self::open_with_limits(path, ParseLimits::default())
103    }
104
105    /// Map and parse a `.gguf` file with explicit limits.
106    pub fn open_with_limits(path: impl AsRef<Path>, limits: ParseLimits) -> Result<Self> {
107        Ok(Self::from_layout(crate::gguf::load_gguf_mmap_with_limits(
108            path, limits,
109        )?))
110    }
111
112    /// Wrap an already-mapped layout.
113    pub fn from_layout(layout: crate::gguf::GgufLayoutMmap) -> Self {
114        let catalog = build_catalog(
115            &layout.path,
116            SourceKind::SingleFile,
117            &layout.metadata,
118            &layout.tensors,
119        );
120        Self { layout, catalog }
121    }
122
123    /// Format-specific mapped layout (page-aligned views, directory checks).
124    pub fn layout(&self) -> &crate::gguf::GgufLayoutMmap {
125        &self.layout
126    }
127
128    /// Unwrap into the format-specific mapped layout.
129    pub fn into_layout(self) -> crate::gguf::GgufLayoutMmap {
130        self.layout
131    }
132}
133
134#[cfg(feature = "mmap")]
135impl Checkpoint for GgufMmapBackend {
136    delegate_catalog!();
137
138    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>> {
139        let info = self.catalog.require(name)?;
140        let bytes = self.layout.tensor_bytes(self.layout.tensor(name)?)?;
141        self.catalog.check_len(info, bytes.len())?;
142        Ok(Cow::Borrowed(bytes))
143    }
144}
145
146/// Shared by owned and mmap backends so both produce identical catalogs.
147fn build_catalog(
148    path: &str,
149    kind: SourceKind,
150    metadata: &GgufMetadata,
151    tensors: &HashMap<String, Tensor>,
152) -> Catalog {
153    let source = gguf_source(path, kind);
154    let file = source.files[0].clone();
155    let infos = tensors
156        .values()
157        .map(|tensor| tensor_info(tensor, &file))
158        .collect();
159    Catalog::new(source, infos, metadata_values(metadata))
160}
161
162fn gguf_source(path: &str, kind: SourceKind) -> CheckpointSource {
163    let as_path = PathBuf::from(path);
164    let (root, file) = match (kind, as_path.file_name()) {
165        // Same root rule as Safetensors: a bare filename resolves against `.`.
166        (SourceKind::SingleFile, Some(name)) => (
167            as_path
168                .parent()
169                .filter(|parent| !parent.as_os_str().is_empty())
170                .unwrap_or_else(|| Path::new("."))
171                .to_path_buf(),
172            name.to_string_lossy().into_owned(),
173        ),
174        _ => (PathBuf::new(), path.to_owned()),
175    };
176    CheckpointSource {
177        format: CheckpointFormat::Gguf,
178        kind,
179        path: as_path,
180        root,
181        index_file: None,
182        files: vec![file],
183    }
184}
185
186fn tensor_info(tensor: &Tensor, file: &str) -> TensorInfo {
187    TensorInfo::new(
188        tensor.name.clone(),
189        normalize_dtype(tensor.dtype, tensor.ggml_type),
190        TensorShape::from_innermost_first(&tensor.dims),
191        tensor.byte_len,
192        TensorLocation::new(file, tensor.relative_offset, Some(tensor.absolute_offset)),
193    )
194    .with_native_dtype(ggml_type_label(tensor.ggml_type))
195}
196
197/// Exact scalar equivalents normalize; every GGML block layout stays packed.
198fn normalize_dtype(dtype: DType, ggml_type: u32) -> TensorDType {
199    match dtype {
200        DType::F32 => TensorDType::F32,
201        DType::F16 => TensorDType::F16,
202        DType::BF16 => TensorDType::BF16,
203        DType::F64 => TensorDType::F64,
204        DType::I8 => TensorDType::I8,
205        DType::I16 => TensorDType::I16,
206        DType::I32 => TensorDType::I32,
207        DType::I64 => TensorDType::I64,
208        _ => TensorDType::GgufPacked { ggml_type },
209    }
210}
211
212/// GGUF typed maps → owned values. Signed entries win over the unsigned
213/// shadow copy the parser also keeps. Arrays are not captured upstream,
214/// and `general.alignment` is consumed as a layout field (see
215/// [`CheckpointMetadata`] docs), so neither appears here.
216fn metadata_values(metadata: &GgufMetadata) -> CheckpointMetadata {
217    let mut out = CheckpointMetadata::new();
218    for (key, value) in &metadata.strings {
219        out.insert(key.clone(), MetadataValue::String(value.clone()));
220    }
221    for (key, &value) in &metadata.numerics {
222        let value = match metadata.signed_numerics.get(key) {
223            Some(&signed) => MetadataValue::Int(signed),
224            None => MetadataValue::UInt(value),
225        };
226        out.insert(key.clone(), value);
227    }
228    for (key, &value) in &metadata.floats_32 {
229        out.insert(key.clone(), MetadataValue::F32(value));
230    }
231    for (key, &value) in &metadata.floats_64 {
232        out.insert(key.clone(), MetadataValue::F64(value));
233    }
234    out
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn signed_metadata_is_not_reported_as_unsigned() {
243        let mut meta = GgufMetadata::default();
244        meta.numerics.insert("neg".into(), (-3i64) as u64);
245        meta.signed_numerics.insert("neg".into(), -3);
246        meta.numerics.insert("big".into(), u64::MAX);
247        meta.floats_64.insert("eps".into(), 1e-6);
248        let values = metadata_values(&meta);
249        assert_eq!(values.get("neg"), Some(&MetadataValue::Int(-3)));
250        assert_eq!(values.get("big"), Some(&MetadataValue::UInt(u64::MAX)));
251        assert_eq!(values.get("eps"), Some(&MetadataValue::F64(1e-6)));
252    }
253
254    #[test]
255    fn quantized_and_internal_types_stay_packed() {
256        assert_eq!(
257            normalize_dtype(DType::Q4_K, 12),
258            TensorDType::GgufPacked { ggml_type: 12 }
259        );
260        assert_eq!(
261            normalize_dtype(DType::IQ3_M_BLOCK, 0x4949_334D),
262            TensorDType::GgufPacked {
263                ggml_type: 0x4949_334D
264            }
265        );
266        assert_eq!(normalize_dtype(DType::BF16, 30), TensorDType::BF16);
267    }
268
269    #[test]
270    fn in_memory_source_uses_label() {
271        let source = gguf_source("mem://unit", SourceKind::InMemory);
272        assert_eq!(source.files, vec!["mem://unit".to_string()]);
273        assert_eq!(source.root, PathBuf::new());
274        let file = gguf_source("/tmp/x/model.gguf", SourceKind::SingleFile);
275        assert_eq!(file.files, vec!["model.gguf".to_string()]);
276        assert_eq!(file.root, PathBuf::from("/tmp/x"));
277    }
278
279    #[test]
280    fn bare_filename_root_is_current_dir() {
281        let source = gguf_source("model.gguf", SourceKind::SingleFile);
282        assert_eq!(source.root, PathBuf::from("."));
283        assert_eq!(source.files, vec!["model.gguf".to_string()]);
284    }
285}