Debian Codegraph @

examples/rezolus_memory.rs

raw symbols SCIP
1 //! Compare the memory requirement of `Histogram`, `SparseHistogram`, and
2 //! `CumulativeROHistogram` for histogram columns in typical Rezolus parquet
3 //! recordings.
4 //!
5 //! Usage:
6 //! ```text
7 //! cargo run --release --example rezolus_memory -- <file.parquet> [<file2.parquet> ...]
8 //! ```
9 //!
10 //! Each parquet file produced by Rezolus stores histograms as
11 //! `List<UInt64>` columns whose field-level metadata carries
12 //! `metric_type = "histogram"`, `grouping_power`, and `max_value_power`.
13 //! Each list element for a given row is the dense bucket vector for that
14 //! sample. This example:
15 //!
16 //! 1. Enumerates every histogram column.
17 //! 2. Reconstructs each sample as a `Histogram` via `Histogram::from_buckets`.
18 //! 3. Converts to `SparseHistogram` and `CumulativeROHistogram`.
19 //! 4. Computes the in-memory footprint (including heap-allocated bucket
20 //! storage) of each representation and prints per-column and overall
21 //! distribution statistics.
22
23 use std::env;
24 use std::fs::File;
25 use std::mem;
26 use std::path::{Path, PathBuf};
27
28 use arrow::array::{Array, ListArray, UInt64Array};
29 use arrow::datatypes::DataType;
30 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
31
32 use histogram::{CumulativeROHistogram, Histogram, SparseHistogram};
33
34 /// Memory footprint, in bytes, of a standard [`Histogram`] including its
35 /// heap-allocated dense bucket array.
36 fn histogram_bytes(h: &Histogram) -> usize {
37 mem::size_of::<Histogram>() + mem::size_of_val(h.as_slice())
38 }
39
40 /// Memory footprint, in bytes, of a [`SparseHistogram`] including the heap
41 /// allocations backing its `index` and `count` vectors.
42 fn sparse_bytes(h: &SparseHistogram) -> usize {
43 mem::size_of::<SparseHistogram>() + mem::size_of_val(h.index()) + mem::size_of_val(h.count())
44 }
45
46 /// Memory footprint, in bytes, of a [`CumulativeROHistogram`] including the
47 /// heap allocations backing its `index` and `count` vectors.
48 fn cumulative_bytes(h: &CumulativeROHistogram) -> usize {
49 mem::size_of::<CumulativeROHistogram>()
50 + mem::size_of_val(h.index())
51 + mem::size_of_val(h.count())
52 }
53
54 #[derive(Default, Clone)]
55 struct Stats {
56 samples: usize,
57 total_buckets: usize,
58 nonzero_buckets_sum: u64,
59 std_bytes_sum: u64,
60 sparse_bytes_sum: u64,
61 cumulative_bytes_sum: u64,
62 std_bytes_min: usize,
63 std_bytes_max: usize,
64 sparse_bytes_min: usize,
65 sparse_bytes_max: usize,
66 cumulative_bytes_min: usize,
67 cumulative_bytes_max: usize,
68 nonzero_buckets_min: usize,
69 nonzero_buckets_max: usize,
70 grouping_power: u8,
71 max_value_power: u8,
72 }
73
74 impl Stats {
75 fn new(grouping_power: u8, max_value_power: u8, total_buckets: usize) -> Self {
76 Self {
77 total_buckets,
78 grouping_power,
79 max_value_power,
80 std_bytes_min: usize::MAX,
81 sparse_bytes_min: usize::MAX,
82 cumulative_bytes_min: usize::MAX,
83 nonzero_buckets_min: usize::MAX,
84 ..Default::default()
85 }
86 }
87
88 fn record(&mut self, nnz: usize, std_b: usize, sparse_b: usize, cumulative_b: usize) {
89 self.samples += 1;
90 self.nonzero_buckets_sum += nnz as u64;
91 self.std_bytes_sum += std_b as u64;
92 self.sparse_bytes_sum += sparse_b as u64;
93 self.cumulative_bytes_sum += cumulative_b as u64;
94 self.nonzero_buckets_min = self.nonzero_buckets_min.min(nnz);
95 self.nonzero_buckets_max = self.nonzero_buckets_max.max(nnz);
96 self.std_bytes_min = self.std_bytes_min.min(std_b);
97 self.std_bytes_max = self.std_bytes_max.max(std_b);
98 self.sparse_bytes_min = self.sparse_bytes_min.min(sparse_b);
99 self.sparse_bytes_max = self.sparse_bytes_max.max(sparse_b);
100 self.cumulative_bytes_min = self.cumulative_bytes_min.min(cumulative_b);
101 self.cumulative_bytes_max = self.cumulative_bytes_max.max(cumulative_b);
102 }
103
104 fn merge(&mut self, other: &Stats) {
105 if other.samples == 0 {
106 return;
107 }
108 if self.samples == 0 {
109 // Clone minimums (and the other fields) from `other` so that the
110 // `Default`-initialized zero-valued minimums don't dominate.
111 *self = other.clone();
112 return;
113 }
114 self.total_buckets = self.total_buckets.max(other.total_buckets);
115 self.samples += other.samples;
116 self.nonzero_buckets_sum += other.nonzero_buckets_sum;
117 self.std_bytes_sum += other.std_bytes_sum;
118 self.sparse_bytes_sum += other.sparse_bytes_sum;
119 self.cumulative_bytes_sum += other.cumulative_bytes_sum;
120 self.nonzero_buckets_min = self.nonzero_buckets_min.min(other.nonzero_buckets_min);
121 self.nonzero_buckets_max = self.nonzero_buckets_max.max(other.nonzero_buckets_max);
122 self.std_bytes_min = self.std_bytes_min.min(other.std_bytes_min);
123 self.std_bytes_max = self.std_bytes_max.max(other.std_bytes_max);
124 self.sparse_bytes_min = self.sparse_bytes_min.min(other.sparse_bytes_min);
125 self.sparse_bytes_max = self.sparse_bytes_max.max(other.sparse_bytes_max);
126 self.cumulative_bytes_min = self.cumulative_bytes_min.min(other.cumulative_bytes_min);
127 self.cumulative_bytes_max = self.cumulative_bytes_max.max(other.cumulative_bytes_max);
128 }
129
130 fn mean_std(&self) -> f64 {
131 self.std_bytes_sum as f64 / self.samples.max(1) as f64
132 }
133 fn mean_sparse(&self) -> f64 {
134 self.sparse_bytes_sum as f64 / self.samples.max(1) as f64
135 }
136 fn mean_cumulative(&self) -> f64 {
137 self.cumulative_bytes_sum as f64 / self.samples.max(1) as f64
138 }
139 fn mean_nnz(&self) -> f64 {
140 self.nonzero_buckets_sum as f64 / self.samples.max(1) as f64
141 }
142 }
143
144 fn format_bytes(b: f64) -> String {
145 if b < 1024.0 {
146 format!("{b:>8.0} B")
147 } else if b < 1024.0 * 1024.0 {
148 format!("{:>8.2} KiB", b / 1024.0)
149 } else {
150 format!("{:>8.2} MiB", b / (1024.0 * 1024.0))
151 }
152 }
153
154 fn process_file(path: &Path, overall: &mut Stats) -> Result<(), Box<dyn std::error::Error>> {
155 println!("\n=== {} ===", path.display());
156
157 let file = File::open(path)?;
158 let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
159 let schema = builder.schema().clone();
160
161 // Find histogram columns and capture their (grouping_power, max_value_power)
162 // parameters. Skip columns that are not List<UInt64> or that are missing
163 // the histogram parameters.
164 let mut columns: Vec<(usize, String, u8, u8)> = Vec::new();
165 for (idx, field) in schema.fields().iter().enumerate() {
166 let meta = field.metadata();
167 if meta.get("metric_type").map(String::as_str) != Some("histogram") {
168 continue;
169 }
170 let (Some(gp), Some(mvp)) = (meta.get("grouping_power"), meta.get("max_value_power"))
171 else {
172 continue;
173 };
174 let (Ok(gp), Ok(mvp)) = (gp.parse::<u8>(), mvp.parse::<u8>()) else {
175 continue;
176 };
177 match field.data_type() {
178 DataType::List(inner) if inner.data_type() == &DataType::UInt64 => {
179 columns.push((idx, field.name().clone(), gp, mvp));
180 }
181 _ => continue,
182 }
183 }
184
185 if columns.is_empty() {
186 println!("(no histogram columns)");
187 return Ok(());
188 }
189
190 let mut per_column: Vec<Stats> = columns
191 .iter()
192 .map(|(_, _, gp, mvp)| {
193 let cfg = histogram::Config::new(*gp, *mvp).expect("valid config");
194 Stats::new(*gp, *mvp, cfg.total_buckets())
195 })
196 .collect();
197
198 let reader = builder.build()?;
199 for batch in reader {
200 let batch = batch?;
201 for (slot, (col_idx, _name, gp, mvp)) in columns.iter().enumerate() {
202 let col = batch.column(*col_idx);
203 let list = col
204 .as_any()
205 .downcast_ref::<ListArray>()
206 .expect("histogram column is List");
207 for row in 0..list.len() {
208 if list.is_null(row) {
209 continue;
210 }
211 let values = list.value(row);
212 let buckets_arr = values
213 .as_any()
214 .downcast_ref::<UInt64Array>()
215 .expect("histogram bucket values are UInt64");
216 let buckets: Vec<u64> = buckets_arr.iter().flatten().collect();
217
218 let Ok(h) = Histogram::from_buckets(*gp, *mvp, buckets) else {
219 continue;
220 };
221 let sparse = SparseHistogram::from(&h);
222 let cumulative = CumulativeROHistogram::from(&h);
223 let nnz = sparse.index().len();
224
225 per_column[slot].record(
226 nnz,
227 histogram_bytes(&h),
228 sparse_bytes(&sparse),
229 cumulative_bytes(&cumulative),
230 );
231 }
232 }
233 }
234
235 // Per-column summary
236 println!(
237 "{:<48} {:>9} {:>4} {:>4} {:>8} {:>10} {:>10} {:>10} {:>7} {:>7}",
238 "column",
239 "samples",
240 "gp",
241 "mvp",
242 "buckets",
243 "std (avg)",
244 "sparse avg",
245 "cumul avg",
246 "sp/std",
247 "cu/std",
248 );
249 println!("{}", "-".repeat(128));
250 for (stats, (_, name, _, _)) in per_column.iter().zip(columns.iter()) {
251 if stats.samples == 0 {
252 continue;
253 }
254 let std_mean = stats.mean_std();
255 let sp_mean = stats.mean_sparse();
256 let cu_mean = stats.mean_cumulative();
257 let sp_ratio = sp_mean / std_mean;
258 let cu_ratio = cu_mean / std_mean;
259 println!(
260 "{:<48} {:>9} {:>4} {:>4} {:>8} {:>14} {:>14} {:>14} {:>6.2}x {:>6.2}x",
261 truncate(name, 48),
262 stats.samples,
263 stats.grouping_power,
264 stats.max_value_power,
265 stats.total_buckets,
266 format_bytes(std_mean),
267 format_bytes(sp_mean),
268 format_bytes(cu_mean),
269 sp_ratio,
270 cu_ratio,
271 );
272 }
273
274 // File-level aggregate
275 let mut file_total = Stats::default();
276 for s in &per_column {
277 file_total.merge(s);
278 }
279
280 if file_total.samples > 0 {
281 println!();
282 println!(
283 "File totals: {} samples across {} histogram columns",
284 file_total.samples,
285 per_column.iter().filter(|s| s.samples > 0).count()
286 );
287 println!(
288 " avg non-zero buckets per sample: {:.1} (range {}..{})",
289 file_total.mean_nnz(),
290 file_total.nonzero_buckets_min,
291 file_total.nonzero_buckets_max,
292 );
293 println!(
294 " total memory (Histogram): {} (avg {}/sample, range {}..{})",
295 format_bytes(file_total.std_bytes_sum as f64),
296 format_bytes(file_total.mean_std()),
297 format_bytes(file_total.std_bytes_min as f64),
298 format_bytes(file_total.std_bytes_max as f64),
299 );
300 println!(
301 " total memory (SparseHistogram): {} (avg {}/sample, range {}..{})",
302 format_bytes(file_total.sparse_bytes_sum as f64),
303 format_bytes(file_total.mean_sparse()),
304 format_bytes(file_total.sparse_bytes_min as f64),
305 format_bytes(file_total.sparse_bytes_max as f64),
306 );
307 println!(
308 " total memory (CumulativeRO): {} (avg {}/sample, range {}..{})",
309 format_bytes(file_total.cumulative_bytes_sum as f64),
310 format_bytes(file_total.mean_cumulative()),
311 format_bytes(file_total.cumulative_bytes_min as f64),
312 format_bytes(file_total.cumulative_bytes_max as f64),
313 );
314 let savings_sparse =
315 1.0 - file_total.sparse_bytes_sum as f64 / file_total.std_bytes_sum as f64;
316 let savings_cumulative =
317 1.0 - file_total.cumulative_bytes_sum as f64 / file_total.std_bytes_sum as f64;
318 println!(
319 " sparse saves {:.1}% vs Histogram; cumulative saves {:.1}%",
320 savings_sparse * 100.0,
321 savings_cumulative * 100.0,
322 );
323 }
324
325 overall.merge(&file_total);
326 Ok(())
327 }
328
329 fn truncate(s: &str, n: usize) -> &str {
330 if s.len() <= n { s } else { &s[..n] }
331 }
332
333 fn main() -> Result<(), Box<dyn std::error::Error>> {
334 let files: Vec<PathBuf> = env::args_os().skip(1).map(PathBuf::from).collect();
335 if files.is_empty() {
336 eprintln!("usage: rezolus_memory <file.parquet> [<file2.parquet> ...]");
337 std::process::exit(2);
338 }
339
340 let mut overall = Stats::default();
341 for path in &files {
342 process_file(path, &mut overall)?;
343 }
344
345 if files.len() > 1 && overall.samples > 0 {
346 println!("\n=== overall across {} files ===", files.len());
347 println!(
348 " {} histogram samples, avg non-zero buckets per sample: {:.1}",
349 overall.samples,
350 overall.mean_nnz(),
351 );
352 println!(
353 " Histogram total: {} (avg {}/sample)",
354 format_bytes(overall.std_bytes_sum as f64),
355 format_bytes(overall.mean_std()),
356 );
357 println!(
358 " SparseHistogram total: {} (avg {}/sample) -> {:.2}x of Histogram",
359 format_bytes(overall.sparse_bytes_sum as f64),
360 format_bytes(overall.mean_sparse()),
361 overall.sparse_bytes_sum as f64 / overall.std_bytes_sum as f64,
362 );
363 println!(
364 " CumulativeRO total: {} (avg {}/sample) -> {:.2}x of Histogram",
365 format_bytes(overall.cumulative_bytes_sum as f64),
366 format_bytes(overall.mean_cumulative()),
367 overall.cumulative_bytes_sum as f64 / overall.std_bytes_sum as f64,
368 );
369 }
370
371 Ok(())
372 }