Skip to main content

run_engine/
run_engine.rs

1//! Runs one serialized engine end to end: load, bind, upload, infer, read back.
2//!
3//! ```text
4//! cargo run --release --example run_engine -- model.engine [--blob input.bin] [--repeat 200]
5//! ```
6//!
7//! `--blob` takes raw little-endian float32 bytes matching the size of the engine's input tensor,
8//! which makes it easy to feed the same preprocessing result into two different runtimes and compare.
9
10use std::time::Instant;
11
12use trt_runner::{cuda, DataType, DeviceBuffer, Engine, IoMode, PinnedBuffer, Stream};
13
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let mut engine_path: Option<String> = None;
16    let mut blob_path: Option<String> = None;
17    let mut repeat: usize = 1;
18    let mut args = std::env::args().skip(1);
19    while let Some(arg) = args.next() {
20        match arg.as_str() {
21            "--blob" => blob_path = args.next(),
22            "--repeat" => repeat = args.next().and_then(|v| v.parse().ok()).unwrap_or(1).max(1),
23            other if engine_path.is_none() => engine_path = Some(other.to_string()),
24            other => return Err(format!("unexpected argument {other:?}").into()),
25        }
26    }
27    let engine_path = engine_path.ok_or("usage: run_engine <engine> [--blob file] [--repeat n]")?;
28
29    let (major, minor, patch) = trt_runner::header_version();
30    println!("compiled against TensorRT {major}.{minor}.{patch}");
31    cuda::set_device(0)?;
32
33    let engine = Engine::from_file(&engine_path)?;
34    println!("{} has {} I/O tensors", engine_path, engine.io().len());
35    for info in engine.io() {
36        println!(
37            "  {:10} {:7} {:?} {:?} {}",
38            info.name,
39            match info.mode {
40                IoMode::Input => "input",
41                IoMode::Output => "output",
42                IoMode::Internal => "internal",
43            },
44            info.dtype,
45            info.shape,
46            info.size_bytes()
47                .map_or_else(|| "dynamic".to_string(), |bytes| format!("{bytes} B"))
48        );
49    }
50
51    let stream = Stream::new()?;
52    let mut context = engine.context()?;
53
54    // one device buffer per bindable tensor, sized from the engine's own metadata
55    let mut buffers = Vec::new();
56    for info in engine.io() {
57        let bytes = info
58            .size_bytes()
59            .ok_or_else(|| trt_runner::Error::DynamicShape {
60                tensor: info.name.clone(),
61                shape: info.shape.clone(),
62            })?;
63        let buffer = DeviceBuffer::zeroed(bytes, &stream)?;
64        buffers.push((info.name.clone(), buffer));
65    }
66    for (name, buffer) in &mut buffers {
67        // SAFETY: the buffers live until after the final synchronised run below.
68        unsafe { context.bind_buffer(name, buffer)? };
69    }
70
71    let input = engine
72        .inputs()
73        .next()
74        .ok_or("the engine has no input tensor to feed")?
75        .clone();
76    let mut host = PinnedBuffer::new(input.size_bytes().unwrap())?;
77    match blob_path {
78        Some(path) => {
79            let raw = std::fs::read(&path)?;
80            if raw.len() != host.size_bytes() {
81                return Err(format!(
82                    "{} holds {} bytes, input wants {}",
83                    path,
84                    raw.len(),
85                    host.size_bytes()
86                )
87                .into());
88            }
89            host.bytes_mut().copy_from_slice(&raw);
90            println!("fed {} bytes from {path}", raw.len());
91        }
92        None => host.f32s_mut().fill(0.5),
93    }
94    let input_buffer = &mut buffers
95        .iter_mut()
96        .find(|(name, _)| *name == input.name)
97        .unwrap()
98        .1;
99    input_buffer.copy_from_host(host.bytes(), &stream)?;
100
101    let mut timings = Vec::with_capacity(repeat);
102    for _ in 0..repeat {
103        let started = Instant::now();
104        context.run(&stream)?;
105        timings.push(started.elapsed().as_secs_f64() * 1000.0);
106    }
107    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
108    let mean = timings.iter().sum::<f64>() / timings.len() as f64;
109    println!(
110        "{} runs: mean {mean:.2} ms  p50 {:.2}  p95 {:.2}  -> {:.1} fps",
111        timings.len(),
112        timings[timings.len() / 2],
113        timings[((timings.len() as f64 * 0.95) as usize).min(timings.len() - 1)],
114        1000.0 / mean
115    );
116
117    for info in engine.outputs() {
118        let buffer = &buffers
119            .iter()
120            .find(|(name, _)| *name == info.name)
121            .unwrap()
122            .1;
123        let mut scratch = vec![0u8; buffer.size_bytes()];
124        // copy_to_host waits for the stream, which is the point: the values below are real.
125        buffer.copy_to_host(&mut scratch, &stream)?;
126        let stats = describe(&scratch, info.dtype);
127        println!("  {} : {}", info.name, stats);
128    }
129    Ok(())
130}
131
132/// Mean, min, max and the first few values, so a wrong result is visible at a glance.
133fn describe(bytes: &[u8], dtype: DataType) -> String {
134    if dtype != DataType::Float32 || bytes.len() % 4 != 0 {
135        return format!("{} bytes of {:?}", bytes.len(), dtype);
136    }
137    let values: Vec<f32> = bytes
138        .chunks_exact(4)
139        .map(|chunk| f32::from_le_bytes(chunk.try_into().expect("four bytes")))
140        .collect();
141    let sum: f64 = values.iter().map(|&v| v as f64).sum();
142    let head: Vec<String> = values.iter().take(6).map(|v| format!("{v:.4}")).collect();
143    format!(
144        "{} values, mean {:.6}, min {:.4}, max {:.4}, first [{}]",
145        values.len(),
146        sum / values.len() as f64,
147        values.iter().cloned().fold(f32::INFINITY, f32::min),
148        values.iter().cloned().fold(f32::NEG_INFINITY, f32::max),
149        head.join(" ")
150    )
151}