Skip to main content

CheckpointMetadata

Struct CheckpointMetadata 

Source
pub struct CheckpointMetadata { /* private fields */ }
Expand description

Sorted metadata key-value store.

Implementations§

Source§

impl CheckpointMetadata

Source

pub fn new() -> Self

Empty store.

Source

pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue)

Insert or replace one entry.

Source

pub fn get(&self, key: &str) -> Option<&MetadataValue>

Look up a value by exact key.

Source

pub fn len(&self) -> usize

Number of entries.

Examples found in repository?
examples/inspect_checkpoint.rs (line 77)
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 154)
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

pub fn is_empty(&self) -> bool

Whether the store is empty.

Source

pub fn keys(&self) -> impl Iterator<Item = &str>

Keys in sorted order.

Source

pub fn iter(&self) -> impl Iterator<Item = (&str, &MetadataValue)>

Entries in sorted key order.

Examples found in repository?
examples/checkpoint_smoke/run.rs (line 164)
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}

Trait Implementations§

Source§

impl Clone for CheckpointMetadata

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CheckpointMetadata

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CheckpointMetadata

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl FromIterator<(String, MetadataValue)> for CheckpointMetadata

Source§

fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl PartialEq for CheckpointMetadata

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for CheckpointMetadata

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.