Skip to main content

Checkpoint

Trait Checkpoint 

Source
pub trait Checkpoint: Send + Sync {
    // Required methods
    fn source(&self) -> &CheckpointSource;
    fn tensors(&self) -> &[TensorInfo];
    fn metadata(&self) -> &CheckpointMetadata;
    fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>>;

    // Provided methods
    fn format(&self) -> CheckpointFormat { ... }
    fn tensor(&self, name: &str) -> Option<&TensorInfo> { ... }
}
Expand description

Consumer-facing, format-independent checkpoint contract.

Object safe: use &dyn Checkpoint or generics. See the module docs for ordering, shape, dtype, and payload guarantees.

Required Methods§

Source

fn source(&self) -> &CheckpointSource

Checkpoint identity: format, input path, root, payload files.

Source

fn tensors(&self) -> &[TensorInfo]

Every tensor, sorted by name.

Source

fn metadata(&self) -> &CheckpointMetadata

Scalar metadata.

Source

fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>>

Raw payload bytes of name, length TensorInfo::byte_len.

Provided Methods§

Source

fn format(&self) -> CheckpointFormat

Container format.

Examples found in repository?
examples/inspect_checkpoint.rs (line 70)
66fn report(ckpt: &dyn Checkpoint, rows: usize) -> Result<()> {
67    let source = ckpt.source();
68    let tensors = ckpt.tensors();
69    let total_bytes: usize = tensors.iter().map(|t| t.byte_len).sum();
70    println!("format:        {} ({})", ckpt.format(), source.kind);
71    println!("path:          {}", source.path.display());
72    println!("root:          {}", source.root.display());
73    if let Some(index) = &source.index_file {
74        println!("index:         {index}");
75    }
76    println!("files:         {}", source.files.len());
77    println!("metadata keys: {}", ckpt.metadata().len());
78    println!("tensors:       {}", tensors.len());
79    println!("payload bytes: {total_bytes}");
80    println!();
81
82    println!(
83        "{:<48} {:<10} {:<10} {:<22} {:>12}  location",
84        "name", "dtype", "native", "shape (outer-first)", "bytes"
85    );
86    for t in tensors.iter().take(rows) {
87        println!(
88            "{:<48} {:<10} {:<10} {:<22} {:>12}  {}@{}",
89            t.name,
90            t.dtype.label(),
91            t.native_dtype,
92            format!("{:?}", t.shape.dims()),
93            t.byte_len,
94            t.location.source,
95            t.location.data_offset,
96        );
97    }
98    if tensors.len() > rows {
99        println!("… {} more (use --all)", tensors.len() - rows);
100    }
101    println!();
102
103    let mut histogram: BTreeMap<String, (usize, usize)> = BTreeMap::new();
104    for t in tensors {
105        let entry = histogram.entry(t.native_dtype.clone()).or_default();
106        entry.0 += 1;
107        entry.1 += t.byte_len;
108    }
109    println!("dtype histogram (native label: count, bytes):");
110    for (dtype, (count, bytes)) in &histogram {
111        println!("  {dtype:<12} {count:>6}  {bytes:>14}");
112    }
113
114    // Probe the smallest non-empty tensor, and skip it past a size cap so
115    // owned (non-mmap) backends never allocate a huge buffer here.
116    let probe = tensors
117        .iter()
118        .filter(|t| t.byte_len > 0)
119        .min_by_key(|t| t.byte_len);
120    if let Some(big) = probe.filter(|t| t.byte_len > PROBE_CAP_BYTES) {
121        println!();
122        println!(
123            "payload probe skipped: smallest tensor '{}' is {} bytes (> {PROBE_CAP_BYTES})",
124            big.name, big.byte_len
125        );
126    } else if let Some(probe) = probe {
127        let bytes = ckpt.tensor_bytes(&probe.name)?;
128        assert_eq!(bytes.len(), probe.byte_len, "payload length mismatch");
129        println!();
130        println!(
131            "payload probe: '{}' -> {} bytes (matches byte_len)",
132            probe.name,
133            bytes.len()
134        );
135    }
136    Ok(())
137}
More examples
Hide additional examples
examples/checkpoint_smoke/run.rs (line 128)
86pub fn main() -> Result<()> {
87    let args: Vec<_> = std::env::args_os().skip(1).collect();
88    if args.len() != 5 {
89        return Err("usage: checkpoint_smoke <gguf|safetensors> <checkpoint> <expected.tsv> <rss-growth-MiB> <heap-peak-MiB>; supply local immutable fixtures, see docs/checkpoint-smoke.md".into());
90    }
91    let format = match args[0].to_str() {
92        Some("gguf") => CheckpointFormat::Gguf,
93        Some("safetensors") => CheckpointFormat::Safetensors,
94        _ => return Err("format must be gguf or safetensors".into()),
95    };
96    let rss_budget = positive_mib(args[3].to_str().ok_or("invalid RSS budget")?)?;
97    let heap_budget = positive_mib(args[4].to_str().ok_or("invalid heap budget")?)?;
98    let path = Path::new(&args[1]);
99    let expected = expectations(Path::new(&args[2]))?;
100    println!(
101        "checkpoint smoke v1 unix_seconds={} platform={}-{} page_size={} invocation={:?}",
102        SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
103        std::env::consts::OS,
104        std::env::consts::ARCH,
105        engram_parser::os_page_size(),
106        std::env::args_os().collect::<Vec<_>>()
107    );
108    println!(
109        "kernel={}",
110        fs::read_to_string("/proc/sys/kernel/osrelease")?.trim()
111    );
112    println!(
113        "budgets rss_growth={rss_budget} heap_peak={heap_budget} repeats={REPEATS} window={WINDOW}"
114    );
115    let baseline = Memory::read()?;
116    baseline.report("baseline");
117    // File-open cost is observed separately; the public mmap open then performs
118    // metadata/index parsing, shard mapping and catalog construction atomically.
119    let input = File::open(path)?;
120    require(
121        input.metadata()?.is_file(),
122        "supply a GGUF file, Safetensors file, or explicit Safetensors index",
123    )?;
124    Memory::read()?.report("file_open");
125    let checkpoint = open_checkpoint_mmap(path)?;
126    Memory::read()?.report("mmap_open_and_metadata_index");
127    require(
128        checkpoint.format() == format,
129        "unexpected checkpoint format",
130    )?;
131    if format == CheckpointFormat::Safetensors {
132        validate_safetensors_source(&checkpoint, &expected)?;
133    }
134    let mut mapped_bytes = 0;
135    let mut smallest_file = u64::MAX;
136    for file in &checkpoint.source().files {
137        let size = fs::metadata(checkpoint.source().root.join(file))?.len();
138        mapped_bytes += size;
139        smallest_file = smallest_file.min(size);
140        println!("file={file:?} bytes={size}");
141    }
142    // A budget that could hide one full shard allocation is not useful evidence.
143    require(
144        (heap_budget as u64) < smallest_file,
145        "heap budget must be smaller than every payload file",
146    )?;
147    require(
148        (rss_budget as u64) < mapped_bytes / 2,
149        "RSS budget must be less than half the checkpoint size",
150    )?;
151    println!(
152        "mapped_file_bytes={mapped_bytes} tensors={} metadata_keys={} samples={}",
153        checkpoint.tensors().len(),
154        checkpoint.metadata().len(),
155        expected.len()
156    );
157    require(
158        checkpoint
159            .tensors()
160            .windows(2)
161            .all(|w| w[0].name < w[1].name),
162        "inventory is not sorted/unique",
163    )?;
164    for (key, value) in checkpoint.metadata().iter() {
165        // Enumerate without printing potentially large tokenizer metadata.
166        std::hint::black_box((key, value));
167    }
168    for e in &expected {
169        verify_metadata(&checkpoint, e)?;
170        println!(
171            "sample name={:?} dtype={} shape={:?} bytes={} shard={:?} file_offset={}",
172            e.name, e.dtype, e.shape, e.bytes, e.shard, e.offset
173        );
174    }
175    Memory::read()?.report("inventory");
176    let mut pointers = Vec::new();
177    let mut fingerprints = Vec::new();
178    for e in &expected {
179        let (ptr, fingerprint) = probe(&checkpoint, e)?;
180        pointers.push(ptr);
181        fingerprints.push(fingerprint);
182        println!(
183            "sample_fingerprint name={:?} fnv1a64={fingerprint:016x}",
184            e.name
185        );
186    }
187    Memory::read()?.report("first_access");
188    for round in 0..REPEATS {
189        for step in 0..expected.len() {
190            let i = if round % 2 == 0 {
191                expected.len() - 1 - step
192            } else {
193                (step + round) % expected.len()
194            };
195            verify_metadata(&checkpoint, &expected[i])?;
196            let (ptr, fingerprint) = probe(&checkpoint, &expected[i])?;
197            require(
198                ptr == pointers[i] && fingerprint == fingerprints[i],
199                "lookup changed pointer or sampled bytes across orders",
200            )?;
201        }
202    }
203    Memory::read()?.report("repeated_access");
204    let mut missing = "__engram_smoke_missing__".to_owned();
205    while checkpoint.tensor(&missing).is_some() {
206        missing.push('_');
207    }
208    require(
209        matches!(
210            checkpoint.tensor_bytes(&missing),
211            Err(ParserError::MissingTensor { .. })
212        ),
213        "missing tensor must return MissingTensor",
214    )?;
215    if format == CheckpointFormat::Safetensors {
216        missing_shard()?;
217    }
218    let final_memory = Memory::read()?;
219    final_memory.report("errors_checked");
220    let rss_growth = final_memory.resident_growth_since(baseline);
221    println!(
222        "observed rss_or_hwm_growth={rss_growth} heap_peak={} largest_allocation={}",
223        final_memory.heap_peak, final_memory.largest
224    );
225    require(
226        rss_growth <= rss_budget,
227        "resident/high-water growth exceeded fixture budget",
228    )?;
229    require(
230        final_memory.heap_peak <= heap_budget,
231        "Rust heap peak exceeded fixture budget",
232    )?;
233    println!(
234        "PASS borrowed payloads; metadata and bounded file reads agree; deterministic lookup; missing-resource errors; memory bounds"
235    );
236    Ok(())
237}
Source

fn tensor(&self, name: &str) -> Option<&TensorInfo>

Look up one tensor by exact name.

Examples found in repository?
examples/checkpoint_smoke/run.rs (line 205)
86pub fn main() -> Result<()> {
87    let args: Vec<_> = std::env::args_os().skip(1).collect();
88    if args.len() != 5 {
89        return Err("usage: checkpoint_smoke <gguf|safetensors> <checkpoint> <expected.tsv> <rss-growth-MiB> <heap-peak-MiB>; supply local immutable fixtures, see docs/checkpoint-smoke.md".into());
90    }
91    let format = match args[0].to_str() {
92        Some("gguf") => CheckpointFormat::Gguf,
93        Some("safetensors") => CheckpointFormat::Safetensors,
94        _ => return Err("format must be gguf or safetensors".into()),
95    };
96    let rss_budget = positive_mib(args[3].to_str().ok_or("invalid RSS budget")?)?;
97    let heap_budget = positive_mib(args[4].to_str().ok_or("invalid heap budget")?)?;
98    let path = Path::new(&args[1]);
99    let expected = expectations(Path::new(&args[2]))?;
100    println!(
101        "checkpoint smoke v1 unix_seconds={} platform={}-{} page_size={} invocation={:?}",
102        SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
103        std::env::consts::OS,
104        std::env::consts::ARCH,
105        engram_parser::os_page_size(),
106        std::env::args_os().collect::<Vec<_>>()
107    );
108    println!(
109        "kernel={}",
110        fs::read_to_string("/proc/sys/kernel/osrelease")?.trim()
111    );
112    println!(
113        "budgets rss_growth={rss_budget} heap_peak={heap_budget} repeats={REPEATS} window={WINDOW}"
114    );
115    let baseline = Memory::read()?;
116    baseline.report("baseline");
117    // File-open cost is observed separately; the public mmap open then performs
118    // metadata/index parsing, shard mapping and catalog construction atomically.
119    let input = File::open(path)?;
120    require(
121        input.metadata()?.is_file(),
122        "supply a GGUF file, Safetensors file, or explicit Safetensors index",
123    )?;
124    Memory::read()?.report("file_open");
125    let checkpoint = open_checkpoint_mmap(path)?;
126    Memory::read()?.report("mmap_open_and_metadata_index");
127    require(
128        checkpoint.format() == format,
129        "unexpected checkpoint format",
130    )?;
131    if format == CheckpointFormat::Safetensors {
132        validate_safetensors_source(&checkpoint, &expected)?;
133    }
134    let mut mapped_bytes = 0;
135    let mut smallest_file = u64::MAX;
136    for file in &checkpoint.source().files {
137        let size = fs::metadata(checkpoint.source().root.join(file))?.len();
138        mapped_bytes += size;
139        smallest_file = smallest_file.min(size);
140        println!("file={file:?} bytes={size}");
141    }
142    // A budget that could hide one full shard allocation is not useful evidence.
143    require(
144        (heap_budget as u64) < smallest_file,
145        "heap budget must be smaller than every payload file",
146    )?;
147    require(
148        (rss_budget as u64) < mapped_bytes / 2,
149        "RSS budget must be less than half the checkpoint size",
150    )?;
151    println!(
152        "mapped_file_bytes={mapped_bytes} tensors={} metadata_keys={} samples={}",
153        checkpoint.tensors().len(),
154        checkpoint.metadata().len(),
155        expected.len()
156    );
157    require(
158        checkpoint
159            .tensors()
160            .windows(2)
161            .all(|w| w[0].name < w[1].name),
162        "inventory is not sorted/unique",
163    )?;
164    for (key, value) in checkpoint.metadata().iter() {
165        // Enumerate without printing potentially large tokenizer metadata.
166        std::hint::black_box((key, value));
167    }
168    for e in &expected {
169        verify_metadata(&checkpoint, e)?;
170        println!(
171            "sample name={:?} dtype={} shape={:?} bytes={} shard={:?} file_offset={}",
172            e.name, e.dtype, e.shape, e.bytes, e.shard, e.offset
173        );
174    }
175    Memory::read()?.report("inventory");
176    let mut pointers = Vec::new();
177    let mut fingerprints = Vec::new();
178    for e in &expected {
179        let (ptr, fingerprint) = probe(&checkpoint, e)?;
180        pointers.push(ptr);
181        fingerprints.push(fingerprint);
182        println!(
183            "sample_fingerprint name={:?} fnv1a64={fingerprint:016x}",
184            e.name
185        );
186    }
187    Memory::read()?.report("first_access");
188    for round in 0..REPEATS {
189        for step in 0..expected.len() {
190            let i = if round % 2 == 0 {
191                expected.len() - 1 - step
192            } else {
193                (step + round) % expected.len()
194            };
195            verify_metadata(&checkpoint, &expected[i])?;
196            let (ptr, fingerprint) = probe(&checkpoint, &expected[i])?;
197            require(
198                ptr == pointers[i] && fingerprint == fingerprints[i],
199                "lookup changed pointer or sampled bytes across orders",
200            )?;
201        }
202    }
203    Memory::read()?.report("repeated_access");
204    let mut missing = "__engram_smoke_missing__".to_owned();
205    while checkpoint.tensor(&missing).is_some() {
206        missing.push('_');
207    }
208    require(
209        matches!(
210            checkpoint.tensor_bytes(&missing),
211            Err(ParserError::MissingTensor { .. })
212        ),
213        "missing tensor must return MissingTensor",
214    )?;
215    if format == CheckpointFormat::Safetensors {
216        missing_shard()?;
217    }
218    let final_memory = Memory::read()?;
219    final_memory.report("errors_checked");
220    let rss_growth = final_memory.resident_growth_since(baseline);
221    println!(
222        "observed rss_or_hwm_growth={rss_growth} heap_peak={} largest_allocation={}",
223        final_memory.heap_peak, final_memory.largest
224    );
225    require(
226        rss_growth <= rss_budget,
227        "resident/high-water growth exceeded fixture budget",
228    )?;
229    require(
230        final_memory.heap_peak <= heap_budget,
231        "Rust heap peak exceeded fixture budget",
232    )?;
233    println!(
234        "PASS borrowed payloads; metadata and bounded file reads agree; deterministic lookup; missing-resource errors; memory bounds"
235    );
236    Ok(())
237}
238
239fn validate_safetensors_source(checkpoint: &dyn Checkpoint, expected: &[Expected]) -> Result<()> {
240    match checkpoint.source().kind {
241        SourceKind::SingleFile => {
242            require(
243                checkpoint.source().files.len() == 1,
244                "single-file Safetensors smoke requires one payload file",
245            )?;
246            require(
247                expected
248                    .iter()
249                    .all(|e| e.shard == checkpoint.source().files[0]),
250                "expected samples must name the single payload file",
251            )?;
252        }
253        SourceKind::ShardIndex => {
254            require(
255                checkpoint.source().files.len() >= 2,
256                "Safetensors shard-index smoke requires multiple shards",
257            )?;
258            require(
259                expected
260                    .iter()
261                    .map(|e| &e.shard)
262                    .collect::<BTreeSet<_>>()
263                    .len()
264                    >= 2,
265                "expected samples must span multiple shards",
266            )?;
267        }
268        _ => {
269            return Err("Safetensors smoke requires a single file or explicit shard index".into());
270        }
271    }
272    Ok(())
273}
274
275fn expected_dtype_label(native: &str) -> &str {
276    match native {
277        "INT4" => "I4",
278        other => other,
279    }
280}
281
282fn verify_metadata(checkpoint: &dyn Checkpoint, e: &Expected) -> Result<()> {
283    let t = checkpoint
284        .tensor(&e.name)
285        .ok_or_else(|| format!("expected tensor {:?} missing", e.name))?;
286    verify_tensor_metadata(t, e)
287}

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Checkpoint for AnyCheckpoint

Source§

impl Checkpoint for GgufBackend

Source§

impl Checkpoint for GgufMmapBackend

Available on crate feature mmap only.
Source§

impl Checkpoint for SafetensorsBackend

Source§

impl Checkpoint for SafetensorsMmapBackend

Available on crate feature mmap only.