Skip to main content

engram_parser/checkpoint/
safetensors.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Safetensors backends for [`Checkpoint`], built on [`crate::safetensors`].
3//!
4//! Discovery, shard path policy, header validation, and the manifest all
5//! come from the existing `safetensors` module; these wrappers only
6//! normalize its records into the shared vocabulary. The manifest,
7//! candidate discovery, and the underlying checkpoint handles stay
8//! reachable through `checkpoint()` / `into_checkpoint()`.
9
10use std::borrow::Cow;
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use super::{
15    Catalog, Checkpoint, CheckpointFormat, CheckpointMetadata, CheckpointSource, MetadataValue,
16    SourceKind, TensorDType, TensorInfo, TensorLocation, TensorShape, delegate_catalog,
17};
18use crate::error::{ParserError, Result};
19use crate::safetensors::{
20    SafetensorsCheckpoint, SafetensorsManifest, SafetensorsTensorRecord,
21    open_safetensors_checkpoint,
22};
23
24/// [`Checkpoint`] over a [`SafetensorsCheckpoint`] (bounded per-tensor reads).
25///
26/// [`Checkpoint::tensor_bytes`] returns [`Cow::Owned`] bytes read from
27/// the owning shard; memory use is bounded by the requested tensor.
28#[derive(Debug)]
29pub struct SafetensorsBackend {
30    checkpoint: SafetensorsCheckpoint,
31    catalog: Catalog,
32}
33
34impl SafetensorsBackend {
35    /// Open a `.safetensors` file, `*.safetensors.index.json`, or shard directory.
36    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
37        let path = path.as_ref();
38        let checkpoint = open_safetensors_checkpoint(path)?;
39        let catalog = build_catalog(path, checkpoint.manifest(), |shard| {
40            checkpoint.shard_data_begin(shard)
41        })?;
42        Ok(Self {
43            checkpoint,
44            catalog,
45        })
46    }
47
48    /// Format-specific handle (manifest, candidates, record lookup).
49    pub fn checkpoint(&self) -> &SafetensorsCheckpoint {
50        &self.checkpoint
51    }
52
53    /// Unwrap into the format-specific handle.
54    pub fn into_checkpoint(self) -> SafetensorsCheckpoint {
55        self.checkpoint
56    }
57}
58
59impl Checkpoint for SafetensorsBackend {
60    delegate_catalog!();
61
62    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>> {
63        let info = self.catalog.require(name)?;
64        let bytes = self.checkpoint.tensor_bytes(name)?;
65        self.catalog.check_len(info, bytes.len())?;
66        Ok(Cow::Owned(bytes))
67    }
68}
69
70/// [`Checkpoint`] over a memory-mapped
71/// [`crate::safetensors::SafetensorsCheckpointMmap`] (borrowed payloads).
72///
73/// Callers must not truncate shard files while the backend is alive
74/// (standard mmap invariant).
75#[cfg(feature = "mmap")]
76#[derive(Debug)]
77pub struct SafetensorsMmapBackend {
78    checkpoint: crate::safetensors::SafetensorsCheckpointMmap,
79    catalog: Catalog,
80}
81
82#[cfg(feature = "mmap")]
83impl SafetensorsMmapBackend {
84    /// Map a `.safetensors` file, `*.safetensors.index.json`, or shard directory.
85    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
86        let path = path.as_ref();
87        let checkpoint = crate::safetensors::open_safetensors_checkpoint_mmap(path)?;
88        let catalog = build_catalog(path, checkpoint.manifest(), |shard| {
89            checkpoint.shard_data_begin(shard)
90        })?;
91        Ok(Self {
92            checkpoint,
93            catalog,
94        })
95    }
96
97    /// Format-specific mapped handle.
98    pub fn checkpoint(&self) -> &crate::safetensors::SafetensorsCheckpointMmap {
99        &self.checkpoint
100    }
101
102    /// Unwrap into the format-specific mapped handle.
103    pub fn into_checkpoint(self) -> crate::safetensors::SafetensorsCheckpointMmap {
104        self.checkpoint
105    }
106}
107
108#[cfg(feature = "mmap")]
109impl Checkpoint for SafetensorsMmapBackend {
110    delegate_catalog!();
111
112    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>> {
113        let info = self.catalog.require(name)?;
114        let bytes = self.checkpoint.tensor_bytes(name)?;
115        self.catalog.check_len(info, bytes.len())?;
116        Ok(Cow::Borrowed(bytes))
117    }
118}
119
120/// Shared by owned and mmap backends so both produce identical catalogs.
121fn build_catalog(
122    path: &Path,
123    manifest: &SafetensorsManifest,
124    data_begin: impl Fn(&str) -> Option<u64>,
125) -> Result<Catalog> {
126    let mut files: Vec<String> = manifest
127        .tensors
128        .iter()
129        .map(|t| t.source_shard.clone())
130        .collect();
131    files.sort();
132    files.dedup();
133
134    let source = CheckpointSource {
135        format: CheckpointFormat::Safetensors,
136        kind: source_kind(path, &manifest.checkpoint.input_kind)?,
137        path: path.to_path_buf(),
138        root: checkpoint_root(path)?,
139        index_file: manifest.checkpoint.index_file.clone(),
140        files,
141    };
142    let tensors = manifest
143        .tensors
144        .iter()
145        .map(|record| {
146            let file_offset = data_begin(&record.source_shard)
147                .and_then(|begin| usize::try_from(begin).ok())
148                .and_then(|begin| begin.checked_add(record.data_offsets[0]));
149            tensor_info(record, file_offset)
150        })
151        .collect();
152    let metadata: CheckpointMetadata = manifest
153        .checkpoint
154        .metadata
155        .iter()
156        .map(|(k, v)| (k.clone(), MetadataValue::String(v.clone())))
157        .collect();
158    Ok(Catalog::new(source, tensors, metadata))
159}
160
161fn tensor_info(record: &SafetensorsTensorRecord, file_offset: Option<usize>) -> TensorInfo {
162    TensorInfo::new(
163        record.name.clone(),
164        normalize_dtype(&record.dtype),
165        TensorShape::outermost_first(record.shape.clone()),
166        record.byte_size,
167        TensorLocation::new(
168            record.source_shard.clone(),
169            record.data_offsets[0],
170            file_offset,
171        ),
172    )
173    .with_native_dtype(record.dtype.clone())
174}
175
176fn normalize_dtype(label: &str) -> TensorDType {
177    match label {
178        "F64" => TensorDType::F64,
179        "F32" => TensorDType::F32,
180        "F16" => TensorDType::F16,
181        "BF16" => TensorDType::BF16,
182        "F8_E4M3" => TensorDType::F8E4M3,
183        "F8_E5M2" => TensorDType::F8E5M2,
184        "I64" => TensorDType::I64,
185        "I32" => TensorDType::I32,
186        "I16" => TensorDType::I16,
187        "I8" => TensorDType::I8,
188        "U64" => TensorDType::U64,
189        "U32" => TensorDType::U32,
190        "U16" => TensorDType::U16,
191        "U8" => TensorDType::U8,
192        "BOOL" => TensorDType::Bool,
193        "I4" | "INT4" => TensorDType::I4,
194        "U4" => TensorDType::U4,
195        other => TensorDType::Other(other.to_owned()),
196    }
197}
198
199fn source_kind(path: &Path, input_kind: &str) -> Result<SourceKind> {
200    match input_kind {
201        "single_file" => Ok(SourceKind::SingleFile),
202        "hf_index" => Ok(SourceKind::ShardIndex),
203        "directory" => Ok(SourceKind::Directory),
204        other => Err(ParserError::UnsupportedFormat {
205            path: path.display().to_string(),
206            reason: format!("unknown Safetensors input kind '{other}'"),
207        }),
208    }
209}
210
211/// Same root rule as Safetensors shard resolution: a directory is its own
212/// root; a file resolves against its parent (or `.`).
213fn checkpoint_root(path: &Path) -> Result<PathBuf> {
214    let metadata = fs::metadata(path).map_err(|source| ParserError::Io {
215        path: path.display().to_string(),
216        source,
217    })?;
218    if metadata.is_dir() {
219        return Ok(path.to_path_buf());
220    }
221    Ok(path
222        .parent()
223        .filter(|parent| !parent.as_os_str().is_empty())
224        .unwrap_or_else(|| Path::new("."))
225        .to_path_buf())
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn dtype_labels_normalize() {
234        assert_eq!(normalize_dtype("BF16"), TensorDType::BF16);
235        assert_eq!(normalize_dtype("INT4"), TensorDType::I4);
236        assert_eq!(normalize_dtype("BOOL"), TensorDType::Bool);
237        assert_eq!(normalize_dtype("C64"), TensorDType::Other("C64".into()));
238    }
239
240    #[test]
241    fn unknown_input_kind_is_rejected() {
242        assert!(source_kind(Path::new("x"), "zip").is_err());
243        assert_eq!(
244            source_kind(Path::new("x"), "hf_index").unwrap(),
245            SourceKind::ShardIndex
246        );
247    }
248}