engram_parser/checkpoint/
open.rs1use 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#[non_exhaustive]
17#[derive(Debug)]
18pub enum AnyCheckpoint {
19 Gguf(GgufBackend),
21 #[cfg(feature = "mmap")]
23 GgufMmap(super::GgufMmapBackend),
24 #[cfg(feature = "safetensors")]
26 Safetensors(super::SafetensorsBackend),
27 #[cfg(all(feature = "safetensors", feature = "mmap"))]
29 SafetensorsMmap(super::SafetensorsMmapBackend),
30}
31
32#[allow(unreachable_patterns)]
35impl AnyCheckpoint {
36 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 pub fn as_gguf(&self) -> Option<&crate::GgufLayout> {
53 match self {
54 Self::Gguf(backend) => Some(backend.layout()),
55 _ => None,
56 }
57 }
58
59 #[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 #[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 #[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
109pub 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#[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 if name.ends_with(".safetensors") || name.ends_with(".safetensors.index.json") {
175 return Ok(Detected::Safetensors);
176 }
177 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
190fn 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}