Skip to main content

engram_parser/gguf/
map.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Memory-mapped GGUF checkpoint access (optional `mmap` feature).
4//!
5//! Maps the file with read-only [`memmap2`] and reuses the same header /
6//! tensor-directory parser as [`super::parse_bytes`]. CUDA host-register is
7//! intentionally out of scope: this crate stays dependency-light and CPU-only.
8//! Callers can still obtain **page-aligned** tensor byte ranges so a later GPU
9//! layer can pin pages without this crate depending on CUDA.
10
11use std::collections::HashMap;
12use std::fs::File;
13use std::path::Path;
14
15use memmap2::{Mmap, MmapOptions};
16
17use super::layout::{GgufLayout, GgufMetadata, parse_layout, tensor_payload_bytes};
18use super::limits::ParseLimits;
19use super::tensor::Tensor;
20use crate::error::{ParserError, Result};
21
22/// GGUF layout backed by a read-only file mapping instead of an owned `Vec<u8>`.
23///
24/// Header, KV metadata, and the tensor directory are identical to
25/// [`GgufLayout`]. Tensor payloads are borrowed from the mapping.
26pub struct GgufLayoutMmap {
27    /// Path the checkpoint was mapped from (kept for error messages).
28    pub path: String,
29    /// Parsed KV metadata.
30    pub metadata: GgufMetadata,
31    /// Name -> tensor directory entry.
32    pub tensors: HashMap<String, Tensor>,
33    /// Byte alignment specified by the file (default 32).
34    pub alignment: usize,
35    /// Absolute byte offset within the mapping where tensor payloads begin.
36    pub tensor_data_offset: usize,
37    mmap: Mmap,
38}
39
40impl std::fmt::Debug for GgufLayoutMmap {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("GgufLayoutMmap")
43            .field("path", &self.path)
44            .field("metadata", &self.metadata)
45            .field("tensors", &self.tensors)
46            .field("alignment", &self.alignment)
47            .field("tensor_data_offset", &self.tensor_data_offset)
48            .field("mmap_len", &self.mmap.len())
49            .finish_non_exhaustive()
50    }
51}
52
53/// Page-aligned view covering a tensor payload inside a mapping.
54///
55/// `pages` starts at an OS-page boundary and covers the tensor; it may
56/// include bytes before/after the payload (and may be truncated at EOF
57/// when the file is smaller than a page). [`Self::tensor_bytes`] returns
58/// the exact payload.
59#[derive(Debug, Clone, Copy)]
60pub struct PageAlignedTensorBytes<'a> {
61    /// Page-aligned (or file-start) range covering the tensor.
62    pub pages: &'a [u8],
63    /// Offset of the exact tensor payload within [`Self::pages`].
64    pub tensor_offset: usize,
65    /// Exact tensor payload length in bytes.
66    pub tensor_len: usize,
67    /// Page size used to compute the range.
68    pub page_size: usize,
69}
70
71impl<'a> PageAlignedTensorBytes<'a> {
72    /// Exact tensor payload, equivalent to [`GgufLayoutMmap::tensor_bytes`].
73    pub fn tensor_bytes(self) -> &'a [u8] {
74        &self.pages[self.tensor_offset..self.tensor_offset + self.tensor_len]
75    }
76}
77
78/// Memory-map a `.gguf` file and parse its header, KV metadata, and tensor
79/// directory without copying the file into a `Vec<u8>`.
80///
81/// Requires the `mmap` cargo feature (`memmap2`). The default
82/// [`super::load_gguf`] path is unchanged.
83pub fn load_gguf_mmap<P: AsRef<Path>>(path: P) -> Result<GgufLayoutMmap> {
84    load_gguf_mmap_with_limits(path, ParseLimits::default())
85}
86
87/// Memory-map a `.gguf` file with an explicit [`ParseLimits`] policy.
88///
89/// Default and mmap readers apply equivalent limits for the same input.
90pub fn load_gguf_mmap_with_limits<P: AsRef<Path>>(
91    path: P,
92    limits: ParseLimits,
93) -> Result<GgufLayoutMmap> {
94    let path_ref = path.as_ref();
95    let path_str = path_ref.display().to_string();
96    let file = File::open(path_ref).map_err(|e| ParserError::Io {
97        path: path_str.clone(),
98        source: e,
99    })?;
100    // SAFETY: `file` is a readable regular-file descriptor. `MmapOptions::map`
101    // creates a read-only mapping. Callers must not truncate the file for the
102    // lifetime of the returned [`GgufLayoutMmap`] (standard mmap invariant).
103    // This crate never host-registers the mapping with CUDA.
104    let mmap = unsafe { MmapOptions::new().map(&file) }.map_err(|e| ParserError::Io {
105        path: path_str.clone(),
106        source: e,
107    })?;
108    let (metadata, tensors, alignment, tensor_data_offset) =
109        parse_layout(&mmap, &path_str, limits)?;
110    Ok(GgufLayoutMmap {
111        path: path_str,
112        metadata,
113        tensors,
114        alignment,
115        tensor_data_offset,
116        mmap,
117    })
118}
119
120impl GgufLayoutMmap {
121    /// Length of the mapped file in bytes.
122    pub fn len(&self) -> usize {
123        self.mmap.len()
124    }
125
126    /// Whether the mapping is empty.
127    pub fn is_empty(&self) -> bool {
128        self.mmap.is_empty()
129    }
130
131    /// Borrowed view of the entire mapped file.
132    pub fn as_bytes(&self) -> &[u8] {
133        &self.mmap
134    }
135
136    /// Return a borrowed slice of the raw tensor payload bytes.
137    pub fn tensor_bytes<'a>(&'a self, tensor: &Tensor) -> Result<&'a [u8]> {
138        tensor_payload_bytes(&self.mmap, &self.path, tensor)
139    }
140
141    /// Lookup a tensor by exact name.
142    pub fn tensor(&self, name: &str) -> Result<&Tensor> {
143        self.tensors
144            .get(name)
145            .ok_or_else(|| ParserError::MissingTensor {
146                name: name.to_owned(),
147                path: self.path.clone(),
148            })
149    }
150
151    /// Page-aligned byte range covering `tensor`, suitable for a later
152    /// CUDA host-register in another crate. Does not register anything here.
153    pub fn tensor_page_aligned_bytes<'a>(
154        &'a self,
155        tensor: &Tensor,
156    ) -> Result<PageAlignedTensorBytes<'a>> {
157        let payload = tensor_payload_bytes(&self.mmap, &self.path, tensor)?;
158        let start = tensor.absolute_offset;
159        let end = start
160            .checked_add(tensor.byte_len)
161            .ok_or_else(|| ParserError::InvalidLayout {
162                path: self.path.clone(),
163                reason: format!("tensor '{}' page-range overflow", tensor.name),
164            })?;
165        let page = os_page_size();
166        if page == 0 {
167            return Err(ParserError::InvalidLayout {
168                path: self.path.clone(),
169                reason: "invalid OS page size: 0".to_string(),
170            });
171        }
172        let aligned_start = (start / page) * page;
173        let aligned_end = align_up_saturating(end, page, self.mmap.len());
174        if aligned_end > self.mmap.len() || aligned_start > self.mmap.len() {
175            return Err(ParserError::InvalidLayout {
176                path: self.path.clone(),
177                reason: format!(
178                    "tensor '{}' page-aligned range exceeds mapping",
179                    tensor.name
180                ),
181            });
182        }
183        let pages = &self.mmap[aligned_start..aligned_end];
184        let tensor_offset = start - aligned_start;
185        debug_assert_eq!(
186            &pages[tensor_offset..tensor_offset + tensor.byte_len],
187            payload
188        );
189        Ok(PageAlignedTensorBytes {
190            pages,
191            tensor_offset,
192            tensor_len: tensor.byte_len,
193            page_size: page,
194        })
195    }
196
197    /// Compare directory metadata with an owned [`GgufLayout`] of the same file.
198    ///
199    /// Checks alignment, tensor-data offset, architecture, and every tensor's
200    /// name, shape, dtype, packed length, and offsets. Does not compare
201    /// payload bytes (callers that need that should use
202    /// [`Self::tensor_bytes`] against [`GgufLayout::tensor_bytes`]).
203    pub fn directory_matches(&self, owned: &GgufLayout) -> bool {
204        self.alignment == owned.alignment
205            && self.tensor_data_offset == owned.tensor_data_offset
206            && self.tensors.len() == owned.tensors.len()
207            && self.metadata.architecture() == owned.metadata.architecture()
208            && self.tensors.iter().all(|(name, mapped)| {
209                owned.tensors.get(name).is_some_and(|owned_t| {
210                    mapped.dims == owned_t.dims
211                        && mapped.dtype == owned_t.dtype
212                        && mapped.ggml_type == owned_t.ggml_type
213                        && mapped.n_elements == owned_t.n_elements
214                        && mapped.byte_len == owned_t.byte_len
215                        && mapped.relative_offset == owned_t.relative_offset
216                        && mapped.absolute_offset == owned_t.absolute_offset
217                })
218            })
219    }
220}
221
222/// OS page size used for [`GgufLayoutMmap::tensor_page_aligned_bytes`].
223pub fn os_page_size() -> usize {
224    match unix_page_size() {
225        Some(n) if n > 0 => n,
226        _ => 4096,
227    }
228}
229
230#[cfg(unix)]
231fn unix_page_size() -> Option<usize> {
232    // POSIX `_SC_PAGESIZE` numeric ids (no `libc` crate).
233    #[cfg(any(target_os = "linux", target_os = "android"))]
234    const SC_PAGESIZE: i32 = 30;
235    #[cfg(any(target_os = "macos", target_os = "ios"))]
236    const SC_PAGESIZE: i32 = 29;
237    #[cfg(target_os = "freebsd")]
238    const SC_PAGESIZE: i32 = 47;
239    #[cfg(any(target_os = "netbsd", target_os = "openbsd"))]
240    const SC_PAGESIZE: i32 = 28;
241    #[cfg(not(any(
242        target_os = "linux",
243        target_os = "android",
244        target_os = "macos",
245        target_os = "ios",
246        target_os = "freebsd",
247        target_os = "netbsd",
248        target_os = "openbsd"
249    )))]
250    const SC_PAGESIZE: i32 = 29;
251
252    unsafe extern "C" {
253        fn sysconf(name: i32) -> i64;
254    }
255
256    // SAFETY: `sysconf(_SC_PAGESIZE)` is a pure query with no preconditions.
257    let n = unsafe { sysconf(SC_PAGESIZE) };
258    (n > 0).then_some(n as usize)
259}
260
261#[cfg(not(unix))]
262fn unix_page_size() -> Option<usize> {
263    None
264}
265
266fn align_up_saturating(value: usize, alignment: usize, limit: usize) -> usize {
267    if alignment <= 1 {
268        return value.min(limit);
269    }
270    value
271        .div_ceil(alignment)
272        .saturating_mul(alignment)
273        .min(limit)
274}