Skip to main content

engram_parser/checkpoint/
open.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Runtime format selection: [`open_checkpoint`] and [`AnyCheckpoint`].
3
4use std::borrow::Cow;
5use std::fs::{self, File};
6use std::io::Read;
7use std::path::Path;
8
9use super::{Checkpoint, CheckpointMetadata, CheckpointSource, GgufBackend, TensorInfo};
10use crate::error::{ParserError, Result};
11
12/// A checkpoint whose backend was chosen at runtime.
13///
14/// Implements [`Checkpoint`] by delegation. The `as_*` accessors return
15/// the format-specific handle when consumers need format-only features.
16#[non_exhaustive]
17#[derive(Debug)]
18pub enum AnyCheckpoint {
19    /// Owned GGUF layout.
20    Gguf(GgufBackend),
21    /// Memory-mapped GGUF layout.
22    #[cfg(feature = "mmap")]
23    GgufMmap(super::GgufMmapBackend),
24    /// Safetensors with bounded owned reads.
25    #[cfg(feature = "safetensors")]
26    Safetensors(super::SafetensorsBackend),
27    /// Memory-mapped Safetensors shards.
28    #[cfg(all(feature = "safetensors", feature = "mmap"))]
29    SafetensorsMmap(super::SafetensorsMmapBackend),
30}
31
32// Accessors below use `_ => None`, which is unreachable when only the
33// default GGUF variant is compiled in.
34#[allow(unreachable_patterns)]
35impl AnyCheckpoint {
36    /// The active backend as a trait object.
37    pub fn as_dyn(&self) -> &dyn Checkpoint {
38        match self {
39            Self::Gguf(backend) => backend,
40            #[cfg(feature = "mmap")]
41            Self::GgufMmap(backend) => backend,
42            #[cfg(feature = "safetensors")]
43            Self::Safetensors(backend) => backend,
44            #[cfg(all(feature = "safetensors", feature = "mmap"))]
45            Self::SafetensorsMmap(backend) => backend,
46        }
47    }
48
49    /// Owned GGUF layout, for
50    /// [`crate::analysis::moe::list_experts`] /
51    /// [`crate::analysis::moe::extract_expert`].
52    pub fn as_gguf(&self) -> Option<&crate::GgufLayout> {
53        match self {
54            Self::Gguf(backend) => Some(backend.layout()),
55            _ => None,
56        }
57    }
58
59    /// Memory-mapped GGUF layout.
60    #[cfg(feature = "mmap")]
61    pub fn as_gguf_mmap(&self) -> Option<&crate::GgufLayoutMmap> {
62        match self {
63            Self::GgufMmap(backend) => Some(backend.layout()),
64            _ => None,
65        }
66    }
67
68    /// Safetensors handle (manifest, MoE candidates, record lookup).
69    #[cfg(feature = "safetensors")]
70    pub fn as_safetensors(&self) -> Option<&crate::safetensors::SafetensorsCheckpoint> {
71        match self {
72            Self::Safetensors(backend) => Some(backend.checkpoint()),
73            _ => None,
74        }
75    }
76
77    /// Memory-mapped Safetensors handle.
78    #[cfg(all(feature = "safetensors", feature = "mmap"))]
79    pub fn as_safetensors_mmap(&self) -> Option<&crate::safetensors::SafetensorsCheckpointMmap> {
80        match self {
81            Self::SafetensorsMmap(backend) => Some(backend.checkpoint()),
82            _ => None,
83        }
84    }
85}
86
87impl Checkpoint for AnyCheckpoint {
88    fn source(&self) -> &CheckpointSource {
89        self.as_dyn().source()
90    }
91
92    fn tensors(&self) -> &[TensorInfo] {
93        self.as_dyn().tensors()
94    }
95
96    fn tensor(&self, name: &str) -> Option<&TensorInfo> {
97        self.as_dyn().tensor(name)
98    }
99
100    fn metadata(&self) -> &CheckpointMetadata {
101        self.as_dyn().metadata()
102    }
103
104    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>> {
105        self.as_dyn().tensor_bytes(name)
106    }
107}
108
109/// Open any supported checkpoint, reading GGUF into memory and serving
110/// Safetensors with bounded per-tensor reads.
111///
112/// Detection, in order:
113/// 1. a directory is a Safetensors shard directory;
114/// 2. a file starting with the `GGUF` magic is GGUF;
115/// 3. a `*.safetensors` file or `*.safetensors.index.json` is Safetensors;
116/// 4. a `*.gguf` file without the magic is handed to the GGUF parser,
117///    which reports the bad header;
118/// 5. anything else is [`ParserError::UnsupportedFormat`].
119///
120/// Safetensors input without the `safetensors` feature returns
121/// [`ParserError::FeatureDisabled`]; no other backend is substituted.
122pub fn open_checkpoint(path: impl AsRef<Path>) -> Result<AnyCheckpoint> {
123    let path = path.as_ref();
124    match detect(path)? {
125        Detected::Gguf => Ok(AnyCheckpoint::Gguf(GgufBackend::open(path)?)),
126        Detected::Safetensors => open_safetensors(path),
127    }
128}
129
130/// Like [`open_checkpoint`], but memory-maps GGUF files and Safetensors
131/// shards so payloads are borrowed from the mappings.
132///
133/// Callers must not truncate the files while the checkpoint is alive.
134#[cfg(feature = "mmap")]
135pub fn open_checkpoint_mmap(path: impl AsRef<Path>) -> Result<AnyCheckpoint> {
136    let path = path.as_ref();
137    match detect(path)? {
138        Detected::Gguf => Ok(AnyCheckpoint::GgufMmap(super::GgufMmapBackend::open(path)?)),
139        Detected::Safetensors => open_safetensors_mmap(path),
140    }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144enum Detected {
145    Gguf,
146    Safetensors,
147}
148
149const GGUF_MAGIC: &[u8; 4] = b"GGUF";
150
151fn detect(path: &Path) -> Result<Detected> {
152    let io_err = |source| ParserError::Io {
153        path: path.display().to_string(),
154        source,
155    };
156    let metadata = fs::metadata(path).map_err(io_err)?;
157    if metadata.is_dir() {
158        return Ok(Detected::Safetensors);
159    }
160
161    let mut magic = [0u8; 4];
162    let mut file = File::open(path).map_err(io_err)?;
163    let read = read_prefix(&mut file, &mut magic).map_err(io_err)?;
164    if read == magic.len() && &magic == GGUF_MAGIC {
165        return Ok(Detected::Gguf);
166    }
167
168    let name = path
169        .file_name()
170        .map(|n| n.to_string_lossy().into_owned())
171        .unwrap_or_default();
172    // Case-sensitive, matching `inspect_safetensors_checkpoint`, so a path
173    // detected here is one the Safetensors backend will actually accept.
174    if name.ends_with(".safetensors") || name.ends_with(".safetensors.index.json") {
175        return Ok(Detected::Safetensors);
176    }
177    // GGUF is identified by magic; the extension only routes a bad header
178    // to the GGUF parser so it can report it.
179    if name.to_ascii_lowercase().ends_with(".gguf") {
180        return Ok(Detected::Gguf);
181    }
182    Err(ParserError::UnsupportedFormat {
183        path: path.display().to_string(),
184        reason: "not a GGUF file (no GGUF magic), .safetensors file, \
185                 .safetensors.index.json index, or Safetensors directory"
186            .to_string(),
187    })
188}
189
190/// Read up to `buf.len()` bytes, tolerating short files.
191fn read_prefix(file: &mut File, buf: &mut [u8]) -> std::io::Result<usize> {
192    let mut filled = 0;
193    while filled < buf.len() {
194        match file.read(&mut buf[filled..])? {
195            0 => break,
196            n => filled += n,
197        }
198    }
199    Ok(filled)
200}
201
202#[cfg(feature = "safetensors")]
203fn open_safetensors(path: &Path) -> Result<AnyCheckpoint> {
204    Ok(AnyCheckpoint::Safetensors(super::SafetensorsBackend::open(
205        path,
206    )?))
207}
208
209#[cfg(not(feature = "safetensors"))]
210fn open_safetensors(path: &Path) -> Result<AnyCheckpoint> {
211    Err(safetensors_disabled(path))
212}
213
214#[cfg(all(feature = "mmap", feature = "safetensors"))]
215fn open_safetensors_mmap(path: &Path) -> Result<AnyCheckpoint> {
216    Ok(AnyCheckpoint::SafetensorsMmap(
217        super::SafetensorsMmapBackend::open(path)?,
218    ))
219}
220
221#[cfg(all(feature = "mmap", not(feature = "safetensors")))]
222fn open_safetensors_mmap(path: &Path) -> Result<AnyCheckpoint> {
223    Err(safetensors_disabled(path))
224}
225
226#[cfg(not(feature = "safetensors"))]
227fn safetensors_disabled(path: &Path) -> ParserError {
228    ParserError::FeatureDisabled {
229        path: path.display().to_string(),
230        feature: "safetensors",
231    }
232}