engram_parser/checkpoint/mod.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Format-independent checkpoint and tensor access.
3//!
4//! [`Checkpoint`] is one consumer-facing contract over GGUF and
5//! Safetensors. Research code can inventory tensors, read metadata, and
6//! fetch raw payload bytes without branching on the container format:
7//!
8//! ```no_run
9//! use engram_parser::{Checkpoint, open_checkpoint};
10//!
11//! fn inventory(ckpt: &dyn Checkpoint) -> engram_parser::Result<()> {
12//! println!("{} from {}", ckpt.format(), ckpt.source().path.display());
13//! for t in ckpt.tensors() {
14//! println!("{} {} {:?} {}B", t.name, t.dtype, t.shape.dims(), t.byte_len);
15//! }
16//! if let Some(first) = ckpt.tensors().first() {
17//! assert_eq!(ckpt.tensor_bytes(&first.name)?.len(), first.byte_len);
18//! }
19//! Ok(())
20//! }
21//!
22//! let ckpt = open_checkpoint("model.gguf")?;
23//! inventory(&ckpt)?;
24//! # Ok::<(), engram_parser::ParserError>(())
25//! ```
26//!
27//! # Backends
28//!
29//! The backends are thin adapters over the existing format modules, which
30//! stay fully reachable:
31//!
32//! | Backend | Wraps | Feature | Payload |
33//! |---|---|---|---|
34//! | [`GgufBackend`] | [`crate::GgufLayout`] | default | borrowed |
35//! | `GgufMmapBackend` | `GgufLayoutMmap` | `mmap` | borrowed |
36//! | `SafetensorsBackend` | `safetensors::SafetensorsCheckpoint` | `safetensors` | owned (bounded read) |
37//! | `SafetensorsMmapBackend` | `safetensors::SafetensorsCheckpointMmap` | `safetensors` + `mmap` | borrowed |
38//!
39//! [`open_checkpoint`] picks a backend at runtime and returns an
40//! [`AnyCheckpoint`], whose `as_*` accessors hand back the
41//! format-specific handle (for example `GgufLayout` for
42//! [`crate::analysis::moe::list_experts`] /
43//! [`crate::analysis::moe::extract_expert`]).
44//!
45//! # Contract
46//!
47//! - **Inventory order.** [`Checkpoint::tensors`] is sorted by name and
48//! identical across calls and across owned/mmap backends of one file.
49//! - **Shape order.** [`TensorShape::dims`] is outermost-first for every
50//! format. GGUF dims (innermost-first on disk) are reversed;
51//! [`TensorShape::native_dims`] restores the on-disk order.
52//! - **Dtypes.** Plain scalar types normalize to shared variants. GGML
53//! quantized layouts stay [`TensorDType::GgufPacked`] with the exact
54//! wire code; [`TensorInfo::native_dtype`] keeps the source label.
55//! - **Payloads.** [`Checkpoint::tensor_bytes`] returns raw bytes exactly
56//! as stored (no decode, no dequant, packed blocks intact), with length
57//! equal to [`TensorInfo::byte_len`]. Borrowed for GGUF and mmap
58//! backends; owned for the bounded-read Safetensors backend.
59//! - **Location.** [`TensorLocation::source`] is relative to
60//! [`CheckpointSource::root`]; `data_offset` is relative to the file's
61//! tensor-data section; `file_offset` is absolute when known.
62//! - **Errors.** Unknown names return [`crate::ParserError::MissingTensor`].
63//!
64//! This module has no numerical execution, device, or MoE concepts.
65//! Model topology and role discovery are out of scope.
66
67use std::borrow::Cow;
68
69use crate::error::{ParserError, Result};
70
71mod gguf;
72mod open;
73#[cfg(feature = "safetensors")]
74mod safetensors;
75mod types;
76
77pub use gguf::GgufBackend;
78#[cfg(feature = "mmap")]
79pub use gguf::GgufMmapBackend;
80#[cfg(feature = "mmap")]
81pub use open::open_checkpoint_mmap;
82pub use open::{AnyCheckpoint, open_checkpoint};
83#[cfg(feature = "safetensors")]
84pub use safetensors::SafetensorsBackend;
85#[cfg(all(feature = "safetensors", feature = "mmap"))]
86pub use safetensors::SafetensorsMmapBackend;
87pub use types::{
88 CheckpointFormat, CheckpointMetadata, CheckpointSource, DimOrder, MetadataValue, SourceKind,
89 TensorDType, TensorInfo, TensorLocation, TensorShape,
90};
91
92/// Consumer-facing, format-independent checkpoint contract.
93///
94/// Object safe: use `&dyn Checkpoint` or generics. See the
95/// [module docs](self) for ordering, shape, dtype, and payload guarantees.
96pub trait Checkpoint: Send + Sync {
97 /// Checkpoint identity: format, input path, root, payload files.
98 fn source(&self) -> &CheckpointSource;
99
100 /// Container format.
101 fn format(&self) -> CheckpointFormat {
102 self.source().format
103 }
104
105 /// Every tensor, sorted by name.
106 fn tensors(&self) -> &[TensorInfo];
107
108 /// Look up one tensor by exact name.
109 fn tensor(&self, name: &str) -> Option<&TensorInfo> {
110 let tensors = self.tensors();
111 tensors
112 .binary_search_by(|t| t.name.as_str().cmp(name))
113 .ok()
114 .map(|index| &tensors[index])
115 }
116
117 /// Scalar metadata.
118 fn metadata(&self) -> &CheckpointMetadata;
119
120 /// Raw payload bytes of `name`, length [`TensorInfo::byte_len`].
121 fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>>;
122}
123
124/// Shared, precomputed state behind every backend.
125#[derive(Debug, Clone)]
126pub(crate) struct Catalog {
127 source: CheckpointSource,
128 tensors: Vec<TensorInfo>,
129 metadata: CheckpointMetadata,
130}
131
132impl Catalog {
133 pub(crate) fn new(
134 source: CheckpointSource,
135 mut tensors: Vec<TensorInfo>,
136 metadata: CheckpointMetadata,
137 ) -> Self {
138 tensors.sort_by(|a, b| a.name.cmp(&b.name));
139 Self {
140 source,
141 tensors,
142 metadata,
143 }
144 }
145
146 /// Fail with `MissingTensor` unless `name` is in the inventory.
147 pub(crate) fn require(&self, name: &str) -> Result<&TensorInfo> {
148 self.tensors
149 .binary_search_by(|t| t.name.as_str().cmp(name))
150 .map(|index| &self.tensors[index])
151 .map_err(|_| ParserError::MissingTensor {
152 name: name.to_owned(),
153 path: self.source.path.display().to_string(),
154 })
155 }
156
157 /// Reject a backend payload whose length disagrees with the inventory.
158 pub(crate) fn check_len(&self, info: &TensorInfo, len: usize) -> Result<()> {
159 if len == info.byte_len {
160 return Ok(());
161 }
162 Err(ParserError::InvalidLayout {
163 path: self.source.path.display().to_string(),
164 reason: format!(
165 "tensor '{}' payload is {len} bytes, inventory says {}",
166 info.name, info.byte_len
167 ),
168 })
169 }
170}
171
172/// Implement the inventory half of [`Checkpoint`] via a `catalog` field.
173macro_rules! delegate_catalog {
174 () => {
175 fn source(&self) -> &$crate::checkpoint::CheckpointSource {
176 &self.catalog.source
177 }
178
179 fn tensors(&self) -> &[$crate::checkpoint::TensorInfo] {
180 &self.catalog.tensors
181 }
182
183 fn metadata(&self) -> &$crate::checkpoint::CheckpointMetadata {
184 &self.catalog.metadata
185 }
186 };
187}
188pub(crate) use delegate_catalog;