Skip to main content

engram_parser/checkpoint/
types.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Engram-owned, format-independent checkpoint value types.
3//!
4//! Every type here is plain data built from std types only. No upstream
5//! (`safetensors`, `memmap2`) type appears in these signatures, and there
6//! are no GPU, execution, or MoE concepts.
7
8use std::collections::BTreeMap;
9use std::fmt;
10use std::path::PathBuf;
11
12use crate::gguf::ggml_type_label;
13
14/// On-disk checkpoint container format.
15#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub enum CheckpointFormat {
18    /// GGUF v3 single-file checkpoint.
19    Gguf,
20    /// Safetensors single file, Hugging Face shard index, or shard directory.
21    Safetensors,
22}
23
24impl CheckpointFormat {
25    /// Stable lowercase name (`"gguf"`, `"safetensors"`).
26    pub const fn as_str(self) -> &'static str {
27        match self {
28            Self::Gguf => "gguf",
29            Self::Safetensors => "safetensors",
30        }
31    }
32}
33
34impl fmt::Display for CheckpointFormat {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(self.as_str())
37    }
38}
39
40/// How the checkpoint input was laid out on disk.
41#[non_exhaustive]
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum SourceKind {
44    /// One file holds every tensor (`.gguf`, single `.safetensors`).
45    SingleFile,
46    /// A Hugging Face `*.safetensors.index.json` shard index.
47    ShardIndex,
48    /// A directory of `.safetensors` shards.
49    Directory,
50    /// An in-memory buffer (for example [`crate::parse_bytes`]).
51    InMemory,
52}
53
54impl SourceKind {
55    /// Stable snake_case name.
56    pub const fn as_str(self) -> &'static str {
57        match self {
58            Self::SingleFile => "single_file",
59            Self::ShardIndex => "shard_index",
60            Self::Directory => "directory",
61            Self::InMemory => "in_memory",
62        }
63    }
64}
65
66impl fmt::Display for SourceKind {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(self.as_str())
69    }
70}
71
72/// Identity of an opened checkpoint: format, input path, and payload files.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct CheckpointSource {
75    /// Container format.
76    pub format: CheckpointFormat,
77    /// Input kind (single file, shard index, directory, in-memory).
78    pub kind: SourceKind,
79    /// Path the checkpoint was opened from, as given by the caller. For
80    /// in-memory GGUF this is the caller-supplied label.
81    pub path: PathBuf,
82    /// Root that [`TensorLocation::source`] paths are relative to.
83    pub root: PathBuf,
84    /// Root-relative index file, when [`SourceKind::ShardIndex`].
85    pub index_file: Option<String>,
86    /// Sorted, de-duplicated root-relative files that hold tensor payloads.
87    pub files: Vec<String>,
88}
89
90/// Order of [`TensorShape::dims`] in the format's native directory.
91#[non_exhaustive]
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum DimOrder {
94    /// Row-major, outermost dimension first (Safetensors, NumPy, PyTorch).
95    OutermostFirst,
96    /// Innermost (fastest-varying) dimension first (GGUF / GGML `ne[]`).
97    InnermostFirst,
98}
99
100/// Tensor shape normalized to **outermost-first** order.
101///
102/// GGUF stores dims innermost-first (`ne[0]` is the contiguous row
103/// length). Those dims are reversed here, so a GGUF `[4096, 32000]`
104/// token embedding becomes `[32000, 4096]`, which is the same order a
105/// Safetensors header uses. [`Self::native_dims`] recovers the on-disk
106/// order losslessly.
107#[derive(Debug, Clone, PartialEq, Eq, Hash)]
108pub struct TensorShape {
109    dims: Vec<usize>,
110    native_order: DimOrder,
111}
112
113impl TensorShape {
114    /// Build a shape from dims that are already outermost-first.
115    pub fn outermost_first(dims: Vec<usize>) -> Self {
116        Self {
117            dims,
118            native_order: DimOrder::OutermostFirst,
119        }
120    }
121
122    /// Build a shape from native innermost-first dims (GGUF `Tensor::dims`).
123    pub fn from_innermost_first(native: &[usize]) -> Self {
124        Self {
125            dims: native.iter().rev().copied().collect(),
126            native_order: DimOrder::InnermostFirst,
127        }
128    }
129
130    /// Dims in outermost-first order.
131    pub fn dims(&self) -> &[usize] {
132        &self.dims
133    }
134
135    /// Order the source format stores dims in.
136    pub fn native_order(&self) -> DimOrder {
137        self.native_order
138    }
139
140    /// Dims in the source format's native order.
141    pub fn native_dims(&self) -> Vec<usize> {
142        match self.native_order {
143            DimOrder::OutermostFirst => self.dims.clone(),
144            DimOrder::InnermostFirst => self.dims.iter().rev().copied().collect(),
145        }
146    }
147
148    /// Number of dimensions.
149    pub fn rank(&self) -> usize {
150        self.dims.len()
151    }
152
153    /// Product of dims, or `None` on overflow. A rank-0 shape has one element.
154    pub fn element_count(&self) -> Option<usize> {
155        self.dims
156            .iter()
157            .try_fold(1usize, |acc, &d| acc.checked_mul(d))
158    }
159}
160
161/// Normalized tensor element type.
162///
163/// Scalar variants are shared by both formats. Packed GGML quantized
164/// layouts keep their exact wire code in [`TensorDType::GgufPacked`], so
165/// they are never conflated with a Safetensors label. Unrecognized labels
166/// are preserved in [`TensorDType::Other`].
167#[non_exhaustive]
168#[derive(Debug, Clone, PartialEq, Eq, Hash)]
169pub enum TensorDType {
170    /// 64-bit float.
171    F64,
172    /// 32-bit float.
173    F32,
174    /// IEEE-754 half float.
175    F16,
176    /// bfloat16.
177    BF16,
178    /// 8-bit float, E4M3.
179    F8E4M3,
180    /// 8-bit float, E5M2.
181    F8E5M2,
182    /// Signed 64-bit integer.
183    I64,
184    /// Signed 32-bit integer.
185    I32,
186    /// Signed 16-bit integer.
187    I16,
188    /// Signed 8-bit integer.
189    I8,
190    /// Unsigned 64-bit integer.
191    U64,
192    /// Unsigned 32-bit integer.
193    U32,
194    /// Unsigned 16-bit integer.
195    U16,
196    /// Unsigned 8-bit integer.
197    U8,
198    /// One-byte boolean.
199    Bool,
200    /// Signed 4-bit integer, two elements per byte (Safetensors `I4`/`INT4`).
201    I4,
202    /// Unsigned 4-bit integer, two elements per byte (Safetensors `U4`).
203    U4,
204    /// A packed GGML quantized block layout (Q4_K, Q8_0, IQ*, …). The raw
205    /// on-wire `ggml_type` code is preserved; payload bytes keep the native
206    /// block layout.
207    GgufPacked {
208        /// GGUF on-wire `ggml_type` code.
209        ggml_type: u32,
210    },
211    /// A dtype label this crate does not normalize (e.g. `C64`, `F8_E8M0`).
212    Other(String),
213}
214
215impl TensorDType {
216    /// Short label (`"F32"`, `"Q4_K"`, or the preserved [`Self::Other`] label).
217    pub fn label(&self) -> &str {
218        match self {
219            Self::F64 => "F64",
220            Self::F32 => "F32",
221            Self::F16 => "F16",
222            Self::BF16 => "BF16",
223            Self::F8E4M3 => "F8_E4M3",
224            Self::F8E5M2 => "F8_E5M2",
225            Self::I64 => "I64",
226            Self::I32 => "I32",
227            Self::I16 => "I16",
228            Self::I8 => "I8",
229            Self::U64 => "U64",
230            Self::U32 => "U32",
231            Self::U16 => "U16",
232            Self::U8 => "U8",
233            Self::Bool => "BOOL",
234            Self::I4 => "I4",
235            Self::U4 => "U4",
236            Self::GgufPacked { ggml_type } => ggml_type_label(*ggml_type),
237            Self::Other(label) => label,
238        }
239    }
240
241    /// `true` for sub-byte or block layouts where bytes ≠ elements × width.
242    pub fn is_packed(&self) -> bool {
243        matches!(self, Self::I4 | Self::U4 | Self::GgufPacked { .. })
244    }
245
246    /// Byte width of one element for plain scalar dtypes; `None` for packed
247    /// and unknown dtypes.
248    pub fn element_size(&self) -> Option<usize> {
249        match self {
250            Self::F64 | Self::I64 | Self::U64 => Some(8),
251            Self::F32 | Self::I32 | Self::U32 => Some(4),
252            Self::F16 | Self::BF16 | Self::I16 | Self::U16 => Some(2),
253            Self::F8E4M3 | Self::F8E5M2 | Self::I8 | Self::U8 | Self::Bool => Some(1),
254            Self::I4 | Self::U4 | Self::GgufPacked { .. } | Self::Other(_) => None,
255        }
256    }
257}
258
259impl fmt::Display for TensorDType {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.write_str(self.label())
262    }
263}
264
265/// Where a tensor payload lives.
266#[derive(Debug, Clone, PartialEq, Eq, Hash)]
267pub struct TensorLocation {
268    /// File holding the payload, relative to [`CheckpointSource::root`].
269    pub source: String,
270    /// Payload start relative to that file's tensor-data section.
271    pub data_offset: usize,
272    /// Payload start from the beginning of the file, when the backend knows it.
273    pub file_offset: Option<usize>,
274}
275
276impl TensorLocation {
277    /// Build a location.
278    pub fn new(source: impl Into<String>, data_offset: usize, file_offset: Option<usize>) -> Self {
279        Self {
280            source: source.into(),
281            data_offset,
282            file_offset,
283        }
284    }
285}
286
287/// Format-independent description of one tensor.
288#[derive(Debug, Clone, PartialEq, Eq, Hash)]
289pub struct TensorInfo {
290    /// Exact tensor name.
291    pub name: String,
292    /// Normalized dtype.
293    pub dtype: TensorDType,
294    /// Dtype label exactly as the source format names it
295    /// (Safetensors header string, or GGUF [`ggml_type_label`]).
296    pub native_dtype: String,
297    /// Outermost-first shape (native order recoverable).
298    pub shape: TensorShape,
299    /// Raw payload length in bytes (packed length for packed dtypes).
300    pub byte_len: usize,
301    /// Payload location.
302    pub location: TensorLocation,
303}
304
305impl TensorInfo {
306    /// Build a tensor description, e.g. for mock inventories in downstream
307    /// tests. `native_dtype` defaults to [`TensorDType::label`].
308    pub fn new(
309        name: impl Into<String>,
310        dtype: TensorDType,
311        shape: TensorShape,
312        byte_len: usize,
313        location: TensorLocation,
314    ) -> Self {
315        let native_dtype = dtype.label().to_owned();
316        Self {
317            name: name.into(),
318            dtype,
319            native_dtype,
320            shape,
321            byte_len,
322            location,
323        }
324    }
325
326    /// Override the native dtype label.
327    #[must_use]
328    pub fn with_native_dtype(mut self, native_dtype: impl Into<String>) -> Self {
329        self.native_dtype = native_dtype.into();
330        self
331    }
332}
333
334/// Owned scalar metadata value.
335///
336/// GGUF numeric metadata is exposed as the parser stores it: unsigned and
337/// bool values as [`Self::UInt`], signed integers as [`Self::Int`], and
338/// floats at their stored width. GGUF arrays are not captured by the
339/// parser and are absent. `general.alignment` is a layout field rather
340/// than metadata: it is never listed (the parser cannot tell a declared
341/// value from the default 32); read the effective value from
342/// `GgufBackend::layout().alignment`. Safetensors metadata is string-only.
343#[non_exhaustive]
344#[derive(Debug, Clone, PartialEq)]
345pub enum MetadataValue {
346    /// String value.
347    String(String),
348    /// Unsigned integer (GGUF `UINT*` and `BOOL`).
349    UInt(u64),
350    /// Signed integer (GGUF `INT*`).
351    Int(i64),
352    /// 32-bit float.
353    F32(f32),
354    /// 64-bit float.
355    F64(f64),
356}
357
358impl MetadataValue {
359    /// String payload, if this is a string.
360    pub fn as_str(&self) -> Option<&str> {
361        match self {
362            Self::String(s) => Some(s),
363            _ => None,
364        }
365    }
366
367    /// Integer payload as `u64`, if it is a non-negative integer.
368    pub fn as_u64(&self) -> Option<u64> {
369        match *self {
370            Self::UInt(v) => Some(v),
371            Self::Int(v) => u64::try_from(v).ok(),
372            _ => None,
373        }
374    }
375
376    /// Numeric payload widened to `f64`.
377    pub fn as_f64(&self) -> Option<f64> {
378        match *self {
379            Self::F32(v) => Some(f64::from(v)),
380            Self::F64(v) => Some(v),
381            Self::UInt(v) => Some(v as f64),
382            Self::Int(v) => Some(v as f64),
383            Self::String(_) => None,
384        }
385    }
386}
387
388impl fmt::Display for MetadataValue {
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        match self {
391            Self::String(s) => f.write_str(s),
392            Self::UInt(v) => write!(f, "{v}"),
393            Self::Int(v) => write!(f, "{v}"),
394            Self::F32(v) => write!(f, "{v}"),
395            Self::F64(v) => write!(f, "{v}"),
396        }
397    }
398}
399
400/// Sorted metadata key-value store.
401#[derive(Debug, Clone, Default, PartialEq)]
402pub struct CheckpointMetadata {
403    entries: BTreeMap<String, MetadataValue>,
404}
405
406impl CheckpointMetadata {
407    /// Empty store.
408    pub fn new() -> Self {
409        Self::default()
410    }
411
412    /// Insert or replace one entry.
413    pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue) {
414        self.entries.insert(key.into(), value);
415    }
416
417    /// Look up a value by exact key.
418    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
419        self.entries.get(key)
420    }
421
422    /// Number of entries.
423    pub fn len(&self) -> usize {
424        self.entries.len()
425    }
426
427    /// Whether the store is empty.
428    pub fn is_empty(&self) -> bool {
429        self.entries.is_empty()
430    }
431
432    /// Keys in sorted order.
433    pub fn keys(&self) -> impl Iterator<Item = &str> {
434        self.entries.keys().map(String::as_str)
435    }
436
437    /// Entries in sorted key order.
438    pub fn iter(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
439        self.entries.iter().map(|(k, v)| (k.as_str(), v))
440    }
441}
442
443impl FromIterator<(String, MetadataValue)> for CheckpointMetadata {
444    fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self {
445        Self {
446            entries: iter.into_iter().collect(),
447        }
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    #[test]
456    fn gguf_shape_round_trips_native_order() {
457        let shape = TensorShape::from_innermost_first(&[4096, 32000]);
458        assert_eq!(shape.dims(), &[32000, 4096]);
459        assert_eq!(shape.native_dims(), vec![4096, 32000]);
460        assert_eq!(shape.native_order(), DimOrder::InnermostFirst);
461        assert_eq!(shape.element_count(), Some(4096 * 32000));
462        assert_eq!(
463            TensorShape::outermost_first(vec![]).element_count(),
464            Some(1)
465        );
466        assert_eq!(
467            TensorShape::outermost_first(vec![usize::MAX, 2]).element_count(),
468            None
469        );
470    }
471
472    #[test]
473    fn dtype_labels_and_packing() {
474        let q4k = TensorDType::GgufPacked { ggml_type: 12 };
475        assert_eq!(q4k.label(), "Q4_K");
476        assert!(q4k.is_packed());
477        assert_eq!(q4k.element_size(), None);
478        assert_eq!(TensorDType::BF16.element_size(), Some(2));
479        assert!(TensorDType::I4.is_packed());
480        assert_eq!(TensorDType::Other("C64".into()).label(), "C64");
481    }
482
483    #[test]
484    fn metadata_value_accessors() {
485        assert_eq!(MetadataValue::Int(-1).as_u64(), None);
486        assert_eq!(MetadataValue::Int(7).as_u64(), Some(7));
487        assert_eq!(MetadataValue::F32(0.5).as_f64(), Some(0.5));
488        assert_eq!(MetadataValue::String("x".into()).as_str(), Some("x"));
489        let meta: CheckpointMetadata = [
490            ("b".to_string(), MetadataValue::UInt(2)),
491            ("a".to_string(), MetadataValue::UInt(1)),
492        ]
493        .into_iter()
494        .collect();
495        assert_eq!(meta.keys().collect::<Vec<_>>(), vec!["a", "b"]);
496    }
497}