pub struct CheckpointMetadata { /* private fields */ }Expand description
Sorted metadata key-value store.
Implementations§
Source§impl CheckpointMetadata
impl CheckpointMetadata
Sourcepub fn insert(&mut self, key: impl Into<String>, value: MetadataValue)
pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue)
Insert or replace one entry.
Sourcepub fn get(&self, key: &str) -> Option<&MetadataValue>
pub fn get(&self, key: &str) -> Option<&MetadataValue>
Look up a value by exact key.
Sourcepub fn len(&self) -> usize
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
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}Sourcepub fn iter(&self) -> impl Iterator<Item = (&str, &MetadataValue)>
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
impl Clone for CheckpointMetadata
Source§impl Debug for CheckpointMetadata
impl Debug for CheckpointMetadata
Source§impl Default for CheckpointMetadata
impl Default for CheckpointMetadata
Source§impl FromIterator<(String, MetadataValue)> for CheckpointMetadata
impl FromIterator<(String, MetadataValue)> for CheckpointMetadata
Source§fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self
Creates a value from an iterator. Read more
Source§impl PartialEq for CheckpointMetadata
impl PartialEq for CheckpointMetadata
impl StructuralPartialEq for CheckpointMetadata
Auto Trait Implementations§
impl Forget for CheckpointMetadata
impl Freeze for CheckpointMetadatawhere
*const LeafNode<String, MetadataValue> is !null: Freeze,
PhantomData<(Owned, LeafOrInternal)>: Freeze,
PhantomData<Box<(String, MetadataValue)>>: Freeze,
impl Move for CheckpointMetadata
impl RefUnwindSafe for CheckpointMetadata
impl Send for CheckpointMetadatawhere
NodeRef<Owned, String, MetadataValue, LeafOrInternal>: Send,
BoxRaw<(String, MetadataValue)>: Send,
impl Sync for CheckpointMetadatawhere
NodeRef<Owned, String, MetadataValue, LeafOrInternal>: Sync,
BoxRaw<(String, MetadataValue)>: Sync,
impl Unpin for CheckpointMetadata
impl UnsafeUnpin for CheckpointMetadatawhere
*const LeafNode<String, MetadataValue> is !null: UnsafeUnpin,
PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin,
PhantomData<Box<(String, MetadataValue)>>: UnsafeUnpin,
impl UnwindSafe for CheckpointMetadata
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more