1use alloc::vec::Vec;
4#[cfg(any(test, feature = "testing"))]
5use core::ops::Range;
6
7use miden_core::{
8 Felt, Word, ZERO,
9 deferred::Digest,
10 program::{MIN_STACK_DEPTH, ProgramInfo, StackInputs, StackOutputs},
11 utils::RowMajorMatrix,
12};
13
14#[cfg(test)]
15use super::trace::MIN_TRACE_LEN;
16use super::{
17 MIDEN_AIR_COUNT, MidenAir, PublicInputs,
18 trace::{MainTrace, RowIndex, eidos_compression::EIDOS_COMPRESSION_CYCLE_LEN},
19};
20
21#[derive(Debug)]
32pub struct VmTrace {
33 main_trace: MainTrace,
34 program_info: ProgramInfo,
35 stack_inputs: StackInputs,
36 stack_outputs: StackOutputs,
37 precompile_root: Digest,
38 trace_len_summary: TraceLenSummary,
39}
40
41impl VmTrace {
42 pub fn new_from_parts(
51 program_info: ProgramInfo,
52 stack_inputs: StackInputs,
53 stack_outputs: StackOutputs,
54 precompile_root: Digest,
55 main_trace: MainTrace,
56 trace_len_summary: TraceLenSummary,
57 ) -> Self {
58 Self {
59 main_trace,
60 program_info,
61 stack_inputs,
62 stack_outputs,
63 precompile_root,
64 trace_len_summary,
65 }
66 }
67
68 pub fn program_info(&self) -> &ProgramInfo {
73 &self.program_info
74 }
75
76 pub fn program_hash(&self) -> &Word {
78 self.program_info.program_hash()
79 }
80
81 pub fn stack_outputs(&self) -> &StackOutputs {
83 &self.stack_outputs
84 }
85
86 pub fn public_inputs(&self) -> PublicInputs {
88 PublicInputs::new(
89 self.program_info.clone(),
90 self.stack_inputs,
91 self.stack_outputs,
92 self.precompile_root,
93 )
94 }
95
96 pub fn to_public_values(&self) -> Vec<Felt> {
98 self.public_inputs().to_elements()
99 }
100
101 pub fn main_trace(&self) -> &MainTrace {
103 &self.main_trace
104 }
105
106 pub fn precompile_root(&self) -> Digest {
108 self.precompile_root
109 }
110
111 pub fn into_outputs(self) -> StackOutputs {
113 self.stack_outputs
114 }
115
116 pub fn init_stack_state(&self) -> StackInputs {
118 self.stack_inputs
119 }
120
121 pub fn last_stack_state(&self) -> StackOutputs {
123 let last_step = RowIndex::from(self.last_step());
124 let mut result = [ZERO; MIN_STACK_DEPTH];
125 for (i, result) in result.iter_mut().enumerate() {
126 *result = self.main_trace.stack_element(i, last_step);
127 }
128 result.into()
129 }
130
131 pub fn get_trace_len(&self) -> usize {
133 self.main_trace.num_rows()
134 }
135
136 pub fn length(&self) -> usize {
138 self.get_trace_len()
139 }
140
141 pub fn trace_len_summary(&self) -> &TraceLenSummary {
143 &self.trace_len_summary
144 }
145
146 pub fn into_air_matrices(
148 self,
149 ) -> (
150 RowMajorMatrix<Felt>,
151 RowMajorMatrix<Felt>,
152 RowMajorMatrix<Felt>,
153 RowMajorMatrix<Felt>,
154 ) {
155 self.main_trace.into_air_matrices()
156 }
157
158 fn last_step(&self) -> usize {
163 self.main_trace.core_height() - 1
164 }
165
166 #[cfg(any(test, feature = "testing"))]
167 pub fn get_column_range(&self, range: Range<usize>) -> Vec<Vec<Felt>> {
168 self.main_trace.get_column_range(range)
169 }
170}
171
172#[derive(Debug, Clone, Copy, Eq, PartialEq, thiserror::Error)]
177pub enum TraceLenSummaryError {
178 #[error("the chiplet row counts add up to more than usize::MAX")]
180 ChipletsRowsOverflow,
181 #[error("padded height of the {air} AIR is zero")]
183 ZeroHeight {
184 air: &'static str,
186 },
187 #[error("padded height {padded_height} of the {air} AIR is below its {rows} unpadded rows")]
189 HeightBelowRows {
190 air: &'static str,
192 padded_height: usize,
194 rows: usize,
196 },
197}
198
199#[derive(Debug, Eq, PartialEq, Clone, Copy)]
204pub struct TraceLenSummary {
205 core_rows: usize,
206 chiplets: ChipletsLengths,
207 eidos_compression_rows: usize,
208 byte_pair_lookup_rows: usize,
209 padded_heights: [usize; MIDEN_AIR_COUNT],
211}
212
213impl TraceLenSummary {
214 pub fn new(
223 core_rows: usize,
224 chiplets: ChipletsLengths,
225 eidos_compression_rows: usize,
226 byte_pair_lookup_rows: usize,
227 padded_heights: [usize; MIDEN_AIR_COUNT],
228 ) -> Result<Self, TraceLenSummaryError> {
229 let chiplets_rows =
230 chiplets.checked_trace_len().ok_or(TraceLenSummaryError::ChipletsRowsOverflow)?;
231 let unpadded_rows: [(&'static str, usize); MIDEN_AIR_COUNT] = [
232 ("Core", core_rows),
233 ("Chiplets", chiplets_rows),
234 ("Eidos compression", eidos_compression_rows),
235 ("byte-pair lookup", byte_pair_lookup_rows),
236 ];
237 for ((air, rows), padded_height) in unpadded_rows.into_iter().zip(padded_heights) {
238 if padded_height == 0 {
239 return Err(TraceLenSummaryError::ZeroHeight { air });
240 }
241 if padded_height < rows {
242 return Err(TraceLenSummaryError::HeightBelowRows { air, padded_height, rows });
243 }
244 }
245
246 Ok(TraceLenSummary {
247 core_rows,
248 chiplets,
249 eidos_compression_rows,
250 byte_pair_lookup_rows,
251 padded_heights,
252 })
253 }
254
255 pub fn core_rows(&self) -> usize {
257 self.core_rows
258 }
259
260 pub fn chiplets(&self) -> ChipletsLengths {
262 self.chiplets
263 }
264
265 pub fn chiplets_rows(&self) -> usize {
267 self.chiplets.trace_len()
268 }
269
270 pub fn eidos_compression_rows(&self) -> usize {
272 self.eidos_compression_rows
273 }
274
275 pub fn eidos_compression_count(&self) -> usize {
278 debug_assert_eq!(self.eidos_compression_rows % EIDOS_COMPRESSION_CYCLE_LEN, 0);
279 self.eidos_compression_rows / EIDOS_COMPRESSION_CYCLE_LEN
280 }
281
282 pub fn byte_pair_lookup_rows(&self) -> usize {
286 self.byte_pair_lookup_rows
287 }
288
289 pub fn trace_len(&self) -> usize {
291 self.core_rows
292 .max(self.chiplets_rows())
293 .max(self.eidos_compression_rows)
294 .max(self.byte_pair_lookup_rows)
295 }
296
297 pub fn core_height(&self) -> usize {
299 self.padded_heights[MidenAir::CORE.instance_index()]
300 }
301
302 pub fn chiplets_height(&self) -> usize {
304 self.padded_heights[MidenAir::CHIPLETS.instance_index()]
305 }
306
307 pub fn eidos_compression_height(&self) -> usize {
309 self.padded_heights[MidenAir::EIDOS_COMPRESSION.instance_index()]
310 }
311
312 pub fn padded_trace_len(&self) -> usize {
314 self.padded_heights.into_iter().max().expect("heights is non-empty")
315 }
316
317 pub fn padded_heights(&self) -> &[usize; MIDEN_AIR_COUNT] {
319 &self.padded_heights
320 }
321
322 pub fn padding_percentage(&self) -> usize {
327 let padded = self.padded_trace_len() as u128;
330 let unpadded = self.trace_len() as u128;
331 ((padded - unpadded) * 100 / padded) as usize
332 }
333}
334
335#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
340pub struct ChipletsLengths {
341 hash_chiplet_len: usize,
342 bitwise_chiplet_len: usize,
343 memory_chiplet_len: usize,
344 ace_chiplet_len: usize,
345 kernel_rom_len: usize,
346}
347
348impl ChipletsLengths {
349 pub fn from_parts(
350 hash_len: usize,
351 bitwise_len: usize,
352 memory_len: usize,
353 ace_len: usize,
354 kernel_len: usize,
355 ) -> Self {
356 ChipletsLengths {
357 hash_chiplet_len: hash_len,
358 bitwise_chiplet_len: bitwise_len,
359 memory_chiplet_len: memory_len,
360 ace_chiplet_len: ace_len,
361 kernel_rom_len: kernel_len,
362 }
363 }
364
365 pub fn hash_chiplet_len(&self) -> usize {
367 self.hash_chiplet_len
368 }
369
370 pub fn bitwise_chiplet_len(&self) -> usize {
372 self.bitwise_chiplet_len
373 }
374
375 pub fn memory_chiplet_len(&self) -> usize {
377 self.memory_chiplet_len
378 }
379
380 pub fn ace_chiplet_len(&self) -> usize {
382 self.ace_chiplet_len
383 }
384
385 pub fn kernel_rom_len(&self) -> usize {
387 self.kernel_rom_len
388 }
389
390 pub fn trace_len(&self) -> usize {
394 self.hash_chiplet_len()
395 + self.bitwise_chiplet_len()
396 + self.memory_chiplet_len()
397 + self.ace_chiplet_len()
398 + self.kernel_rom_len()
399 + 1
400 }
401
402 pub fn checked_trace_len(&self) -> Option<usize> {
404 self.hash_chiplet_len()
405 .checked_add(self.bitwise_chiplet_len())?
406 .checked_add(self.memory_chiplet_len())?
407 .checked_add(self.ace_chiplet_len())?
408 .checked_add(self.kernel_rom_len())?
409 .checked_add(1)
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
418 fn trace_len_summary_reports_eidos_compression_count() {
419 let summary = TraceLenSummary::new(
420 0,
421 ChipletsLengths::default(),
422 3 * EIDOS_COMPRESSION_CYCLE_LEN,
423 0,
424 [
425 MIN_TRACE_LEN,
426 MIN_TRACE_LEN,
427 (3 * EIDOS_COMPRESSION_CYCLE_LEN).next_power_of_two().max(MIN_TRACE_LEN),
428 MIN_TRACE_LEN,
429 ],
430 )
431 .expect("valid padded heights");
432
433 assert_eq!(summary.eidos_compression_rows(), 3 * EIDOS_COMPRESSION_CYCLE_LEN);
434 assert_eq!(summary.eidos_compression_count(), 3);
435 }
436
437 #[test]
438 fn trace_len_summary_records_four_air_heights_in_instance_order() {
439 let heights = [MIN_TRACE_LEN, 2 * MIN_TRACE_LEN, 4 * MIN_TRACE_LEN, 1 << 16];
440 let summary = TraceLenSummary::new(
441 17,
442 ChipletsLengths::from_parts(19, 0, 0, 0, 0),
443 3 * EIDOS_COMPRESSION_CYCLE_LEN,
444 1 << 16,
445 heights,
446 )
447 .expect("valid padded heights");
448
449 assert_eq!(summary.core_rows(), 17);
450 assert_eq!(summary.chiplets_rows(), 20);
452 assert_eq!(summary.eidos_compression_rows(), 3 * EIDOS_COMPRESSION_CYCLE_LEN);
453 assert_eq!(summary.byte_pair_lookup_rows(), 1 << 16);
454 assert_eq!(summary.padded_heights(), &heights);
455 assert_eq!(summary.core_height(), heights[0]);
456 assert_eq!(summary.chiplets_height(), heights[1]);
457 assert_eq!(summary.eidos_compression_height(), heights[2]);
458 assert_eq!(summary.padded_trace_len(), 1 << 16);
459 }
460
461 #[test]
462 fn trace_len_summary_rejects_zero_padded_height() {
463 for air in 0..MIDEN_AIR_COUNT {
464 let mut heights = [MIN_TRACE_LEN; MIDEN_AIR_COUNT];
465 heights[air] = 0;
466 let result = TraceLenSummary::new(0, ChipletsLengths::default(), 0, 0, heights);
467 assert!(
468 matches!(result, Err(TraceLenSummaryError::ZeroHeight { .. })),
469 "AIR {air}: {result:?}",
470 );
471 }
472 }
473
474 #[test]
475 fn trace_len_summary_rejects_padded_height_below_rows() {
476 let rows = 2 * MIN_TRACE_LEN;
477 let result = TraceLenSummary::new(
478 rows,
479 ChipletsLengths::default(),
480 0,
481 0,
482 [MIN_TRACE_LEN; MIDEN_AIR_COUNT],
483 );
484
485 assert_eq!(
486 result,
487 Err(TraceLenSummaryError::HeightBelowRows {
488 air: "Core",
489 padded_height: MIN_TRACE_LEN,
490 rows,
491 })
492 );
493 }
494
495 #[test]
496 fn trace_len_summary_padding_percentage_for_valid_heights() {
497 let heights = [MIN_TRACE_LEN; MIDEN_AIR_COUNT];
498
499 let half_full =
500 TraceLenSummary::new(MIN_TRACE_LEN / 2, ChipletsLengths::default(), 0, 0, heights)
501 .expect("valid padded heights");
502 assert_eq!(half_full.padding_percentage(), 50);
503
504 let full = TraceLenSummary::new(MIN_TRACE_LEN, ChipletsLengths::default(), 0, 0, heights)
505 .expect("valid padded heights");
506 assert_eq!(full.padding_percentage(), 0);
507 }
508
509 #[test]
510 fn trace_len_summary_padding_percentage_does_not_overflow_for_huge_heights() {
511 let heights = [1usize << (usize::BITS - 1); MIDEN_AIR_COUNT];
512 let summary = TraceLenSummary::new(0, ChipletsLengths::default(), 0, 0, heights)
513 .expect("valid padded heights");
514
515 assert_eq!(summary.padding_percentage(), 99);
518 }
519
520 #[test]
521 fn trace_len_summary_rejects_chiplets_row_count_overflow() {
522 for chiplets in [
523 ChipletsLengths::from_parts(usize::MAX, 0, 0, 0, 0),
525 ChipletsLengths::from_parts(usize::MAX, 1, 0, 0, 0),
527 ] {
528 let result = TraceLenSummary::new(0, chiplets, 0, 0, [MIN_TRACE_LEN; MIDEN_AIR_COUNT]);
529 assert_eq!(result, Err(TraceLenSummaryError::ChipletsRowsOverflow));
530 }
531 }
532}