Skip to main content

inspect_checkpoint/
inspect_checkpoint.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Format-agnostic tensor inventory for GGUF or Safetensors checkpoints.
3//!
4//! After `open_checkpoint`, everything goes through `&dyn Checkpoint`;
5//! there is no format branching in the report.
6//!
7//! # Usage
8//!
9//! ```bash
10//! cargo run --example inspect_checkpoint -- /path/to/model.gguf
11//! cargo run --features safetensors --example inspect_checkpoint -- /path/to/hf-model-dir
12//! cargo run --all-features --example inspect_checkpoint -- --mmap --all /path/to/model.safetensors
13//! ```
14//!
15//! Flags: `--all` prints every tensor (default: first 32), `--mmap`
16//! memory-maps instead of reading (requires the `mmap` feature).
17//! CPU-only; payloads are read as raw bytes, never decoded.
18
19use std::collections::BTreeMap;
20use std::env;
21use std::process::ExitCode;
22
23use engram_parser::{AnyCheckpoint, Checkpoint, Result, open_checkpoint};
24
25const DEFAULT_ROWS: usize = 32;
26/// Largest payload the probe will read (64 MiB).
27const PROBE_CAP_BYTES: usize = 64 * 1024 * 1024;
28
29struct Args {
30    path: String,
31    all: bool,
32    mmap: bool,
33}
34
35fn parse_args() -> std::result::Result<Args, String> {
36    let (mut path, mut all, mut mmap) = (None, false, false);
37    for arg in env::args().skip(1) {
38        match arg.as_str() {
39            "--all" => all = true,
40            "--mmap" => mmap = true,
41            "--" => {}
42            "-h" | "--help" => return Err(String::new()),
43            flag if flag.starts_with("--") => return Err(format!("unknown flag {flag}")),
44            other if path.is_none() => path = Some(other.to_owned()),
45            other => return Err(format!("unexpected argument {other}")),
46        }
47    }
48    let path = path.ok_or_else(|| "missing checkpoint path".to_string())?;
49    Ok(Args { path, all, mmap })
50}
51
52fn open(args: &Args) -> Result<AnyCheckpoint> {
53    if args.mmap {
54        #[cfg(feature = "mmap")]
55        return engram_parser::open_checkpoint_mmap(&args.path);
56        #[cfg(not(feature = "mmap"))]
57        return Err(engram_parser::ParserError::FeatureDisabled {
58            path: args.path.clone(),
59            feature: "mmap",
60        });
61    }
62    open_checkpoint(&args.path)
63}
64
65/// The whole report sees only the shared contract.
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}
138
139fn main() -> ExitCode {
140    let args = match parse_args() {
141        Ok(args) => args,
142        Err(msg) => {
143            if !msg.is_empty() {
144                eprintln!("error: {msg}");
145            }
146            eprintln!(
147                "usage: cargo run --example inspect_checkpoint -- [--all] [--mmap] <checkpoint>"
148            );
149            return ExitCode::from(2);
150        }
151    };
152    let rows = if args.all { usize::MAX } else { DEFAULT_ROWS };
153    match open(&args).and_then(|ckpt| report(&ckpt, rows)) {
154        Ok(()) => ExitCode::SUCCESS,
155        Err(e) => {
156            eprintln!("error: {e}");
157            ExitCode::from(1)
158        }
159    }
160}