trt-runner 0.1.0

Minimal TensorRT 10 inference runner: deserialize an engine, bind I/O tensors, enqueue V3. No bindings generator, no runtime dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Loading an engine, reading its I/O tensors, and running one execution context.

use std::ffi::CStr;
use std::os::raw::c_void;
use std::path::Path;

use crate::cuda::DeviceBuffer;
use crate::cuda::Stream;
use crate::error::{last_message, trt_check, Error};
use crate::ffi;
use crate::Result;

/// Maximum dimensions TensorRT allows for one tensor.
pub const MAX_DIMS: usize = 8;

/// Element type of a tensor, as reported by the engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataType {
    /// `f32`.
    Float32,
    /// IEEE half.
    Float16,
    /// Signed 8 bit integer.
    Int8,
    /// `i32`.
    Int32,
    /// One byte per value.
    Bool,
    /// Unsigned 8 bit integer.
    UInt8,
    /// 8 bit floating point.
    Fp8,
    /// Brain float.
    BFloat16,
    /// `i64`.
    Int64,
    /// Two values per byte, so a whole-tensor byte count is not `elements * size`.
    Int4,
}

impl DataType {
    fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::Float32,
            1 => Self::Float16,
            2 => Self::Int8,
            3 => Self::Int32,
            4 => Self::Bool,
            5 => Self::UInt8,
            6 => Self::Fp8,
            7 => Self::BFloat16,
            8 => Self::Int64,
            9 => Self::Int4,
            _ => return None,
        })
    }

    /// Bytes per element, or `None` for the sub-byte types.
    pub fn element_bytes(self) -> Option<usize> {
        match self {
            Self::Float32 | Self::Int32 | Self::Int64 => Some(4),
            Self::Float16 | Self::BFloat16 => Some(2),
            Self::Int8 | Self::Bool | Self::UInt8 | Self::Fp8 => Some(1),
            Self::Int4 => None,
        }
    }
}

/// Whether the engine reads or writes a tensor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IoMode {
    /// The caller writes it.
    Input,
    /// The caller reads it back.
    Output,
    /// Present in the graph but neither bound by the caller nor read back.
    Internal,
}

/// One I/O tensor of an engine: name, direction, element type and declared shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TensorInfo {
    /// Engine side name, e.g. `images` or `output0`.
    pub name: String,
    /// Direction of the tensor.
    pub mode: IoMode,
    /// Element type.
    pub dtype: DataType,
    /// Dimensions as declared in the engine. `-1` marks a dynamic dimension.
    pub shape: Vec<i64>,
}

impl TensorInfo {
    /// Number of elements, or `None` when any dimension is dynamic.
    pub fn elements(&self) -> Option<usize> {
        if self.shape.iter().any(|&dim| dim < 0) {
            return None;
        }
        Some(self.shape.iter().map(|&dim| dim as usize).product())
    }

    /// Size in bytes, or `None` for dynamic shapes and sub-byte element types.
    pub fn size_bytes(&self) -> Option<usize> {
        Some(self.elements()? * self.dtype.element_bytes()?)
    }

    /// True when the shape is fixed, which is the common case for an exported detection model.
    pub fn is_static(&self) -> bool {
        self.elements().is_some()
    }
}

/// The TensorRT header version this crate was compiled against.
pub fn header_version() -> (u32, u32, u32) {
    unsafe {
        (
            ffi::trt_version_major() as u32,
            ffi::trt_version_minor() as u32,
            ffi::trt_version_patch() as u32,
        )
    }
}

/// A deserialized engine plus the runtime that produced it.
///
/// Engines are built for one GPU, one driver and one exact TensorRT build: an engine built elsewhere
/// will usually fail to load here, and that failure is reported as
/// [`Error::TensorRt`][Error::TensorRt] rather than a crash.
#[derive(Debug)]
pub struct Engine {
    // declaration order matters on drop: tensors, then engine, then the runtime that owns it
    io: Vec<TensorInfo>,
    engine: *mut c_void,
    runtime: *mut c_void,
}

impl Engine {
    /// Reads and deserializes a serialized engine.
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let bytes = std::fs::read(path.as_ref())?;
        Self::from_bytes(&bytes)
    }

    /// Deserializes engine bytes already in memory.
    ///
    /// `verbosity` follows TensorRT's logger levels: 2 keeps warnings and errors, 4 is very chatty.
    pub fn from_bytes_with_verbosity(bytes: &[u8], verbosity: i32) -> Result<Self> {
        let runtime = unsafe { ffi::trt_runtime_create(verbosity) };
        if runtime.is_null() {
            return Err(Error::TensorRt {
                call: "createInferRuntime",
                message: last_message(),
            });
        }
        let engine = unsafe {
            ffi::trt_runtime_deserialize(runtime, bytes.as_ptr() as *const c_void, bytes.len())
        };
        if engine.is_null() {
            let message = last_message();
            unsafe { ffi::trt_runtime_destroy(runtime) };
            return Err(Error::TensorRt {
                call: "deserializeCudaEngine",
                message,
            });
        }
        let io = match collect_io(engine) {
            Ok(io) => io,
            Err(error) => {
                unsafe {
                    ffi::trt_engine_destroy(engine);
                    ffi::trt_runtime_destroy(runtime);
                }
                return Err(error);
            }
        };
        Ok(Self {
            io,
            engine,
            runtime,
        })
    }

    /// Deserializes with warnings and errors only.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::from_bytes_with_verbosity(bytes, 2)
    }

    /// Every tensor the caller can bind, in engine order.
    pub fn io(&self) -> &[TensorInfo] {
        &self.io
    }

    /// Looks a tensor up by name.
    pub fn tensor(&self, name: &str) -> Option<&TensorInfo> {
        self.io.iter().find(|info| info.name == name)
    }

    /// Tensors the caller must fill.
    pub fn inputs(&self) -> impl Iterator<Item = &TensorInfo> {
        self.io.iter().filter(|info| info.mode == IoMode::Input)
    }

    /// Tensors the caller reads back.
    pub fn outputs(&self) -> impl Iterator<Item = &TensorInfo> {
        self.io.iter().filter(|info| info.mode == IoMode::Output)
    }

    /// Names of all I/O tensors, for error messages.
    pub fn tensor_names(&self) -> Vec<String> {
        self.io.iter().map(|info| info.name.clone()).collect()
    }

    /// Creates an execution context. One context handles one shape combination at a time and is not
    /// `Sync`; create one per thread instead.
    pub fn context(&self) -> Result<Context<'_>> {
        let context = create_context(self.engine)?;
        Ok(Context {
            context,
            engine: self,
        })
    }

    /// Consumes the engine into an [`OwnedContext`], which keeps the engine and the runtime alive
    /// beside the execution context. This is the shape a long lived runner usually wants: one value
    /// to store in a struct, without a lifetime parameter chasing it.
    pub fn into_context(self) -> Result<OwnedContext> {
        let context = create_context(self.engine)?;
        let owned = OwnedContext {
            io: self.io.clone(),
            context,
            engine: self.engine,
            runtime: self.runtime,
        };
        // the three raw handles now belong to the OwnedContext, which drops them in the same order
        std::mem::forget(self);
        Ok(owned)
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        unsafe {
            ffi::trt_engine_destroy(self.engine);
            ffi::trt_runtime_destroy(self.runtime);
        }
    }
}

fn create_context(engine: *mut c_void) -> Result<*mut c_void> {
    let context = unsafe { ffi::trt_context_create(engine) };
    if context.is_null() {
        return Err(Error::TensorRt {
            call: "createExecutionContext",
            message: last_message(),
        });
    }
    Ok(context)
}

/// A bound execution context. Borrows the engine so it can never outlive it.
#[derive(Debug)]
pub struct Context<'engine> {
    context: *mut c_void,
    engine: &'engine Engine,
}

impl<'engine> Context<'engine> {
    /// The engine this context came from.
    pub fn engine(&self) -> &'engine Engine {
        self.engine
    }

    /// Selects an optimization profile. Only needed for engines with more than one dynamic shape
    /// profile, and only before [`Context::set_shape`].
    pub fn set_profile(&mut self, index: i32, stream: &Stream) -> Result<()> {
        set_profile(self.context, index, stream)
    }

    /// Declares the shape of a dynamic input.
    pub fn set_shape(&mut self, name: &str, shape: &[i64]) -> Result<()> {
        set_shape(self.context, name, shape)
    }

    /// Points a tensor at device memory. The buffer has to stay alive, and stay put, until the last
    /// `enqueue` using this binding has been synchronised.
    ///
    /// # Safety
    /// `address` must be a device pointer with at least `bytes` readable or writable, depending on
    /// the direction of the tensor.
    pub unsafe fn bind_raw(
        &mut self,
        name: &str,
        address: *mut c_void,
        bytes: usize,
    ) -> Result<()> {
        bind_raw(self.context, self.engine.io(), name, address, bytes)
    }

    /// Binds a [`DeviceBuffer`] the caller allocated, checking its size against the engine.
    ///
    /// # Safety
    /// Same contract as [`Context::bind_raw`]: `buffer` must outlive every enqueue using the binding.
    pub unsafe fn bind_buffer(&mut self, name: &str, buffer: &DeviceBuffer) -> Result<()> {
        unsafe { self.bind_raw(name, buffer.as_ptr() as *mut c_void, buffer.size_bytes()) }
    }

    /// Queues the network on `stream` and returns immediately. The output buffers are not readable
    /// until `stream` reports the work finished.
    pub fn enqueue(&mut self, stream: &Stream) -> Result<()> {
        enqueue(self.context, stream)
    }

    /// Queues the network and blocks until it is done.
    pub fn run(&mut self, stream: &Stream) -> Result<()> {
        run(self.context, stream)
    }
}

impl Drop for Context<'_> {
    fn drop(&mut self) {
        unsafe { ffi::trt_context_destroy(self.context) };
    }
}

/// An execution context that owns the engine and runtime behind it, so it can be stored in a struct
/// without a lifetime parameter.
#[derive(Debug)]
pub struct OwnedContext {
    io: Vec<TensorInfo>,
    context: *mut c_void,
    // kept alive, and destroyed after, the context
    engine: *mut c_void,
    runtime: *mut c_void,
}

impl OwnedContext {
    /// Every bindable tensor.
    pub fn io(&self) -> &[TensorInfo] {
        &self.io
    }

    /// Looks a tensor up by name.
    pub fn tensor(&self, name: &str) -> Option<&TensorInfo> {
        self.io.iter().find(|info| info.name == name)
    }

    /// Tensors the caller must fill.
    pub fn inputs(&self) -> impl Iterator<Item = &TensorInfo> {
        self.io.iter().filter(|info| info.mode == IoMode::Input)
    }

    /// Tensors the caller reads back.
    pub fn outputs(&self) -> impl Iterator<Item = &TensorInfo> {
        self.io.iter().filter(|info| info.mode == IoMode::Output)
    }

    /// See [`Context::set_profile`].
    pub fn set_profile(&mut self, index: i32, stream: &Stream) -> Result<()> {
        set_profile(self.context, index, stream)
    }

    /// See [`Context::set_shape`].
    pub fn set_shape(&mut self, name: &str, shape: &[i64]) -> Result<()> {
        set_shape(self.context, name, shape)
    }

    /// See [`Context::bind_raw`].
    ///
    /// # Safety
    /// `address` must be a device pointer that stays valid for the lifetime of the binding.
    pub unsafe fn bind_raw(
        &mut self,
        name: &str,
        address: *mut c_void,
        bytes: usize,
    ) -> Result<()> {
        bind_raw(self.context, &self.io, name, address, bytes)
    }

    /// See [`Context::bind_buffer`].
    ///
    /// # Safety
    /// `buffer` must outlive every enqueue that uses the binding.
    pub unsafe fn bind_buffer(&mut self, name: &str, buffer: &DeviceBuffer) -> Result<()> {
        unsafe { self.bind_raw(name, buffer.as_ptr() as *mut c_void, buffer.size_bytes()) }
    }

    /// See [`Context::enqueue`].
    pub fn enqueue(&mut self, stream: &Stream) -> Result<()> {
        enqueue(self.context, stream)
    }

    /// See [`Context::run`].
    pub fn run(&mut self, stream: &Stream) -> Result<()> {
        run(self.context, stream)
    }
}

// A context belongs to one thread at a time and is not `Sync`; handing ownership to another thread
// is fine as long as that thread has the CUDA context current, which is the caller's job.
unsafe impl Send for OwnedContext {}

impl Drop for OwnedContext {
    fn drop(&mut self) {
        unsafe {
            ffi::trt_context_destroy(self.context);
            ffi::trt_engine_destroy(self.engine);
            ffi::trt_runtime_destroy(self.runtime);
        }
    }
}

fn set_profile(context: *mut c_void, index: i32, stream: &Stream) -> Result<()> {
    trt_check(
        unsafe { ffi::trt_context_set_profile(context, index, stream.as_raw()) },
        "setOptimizationProfileAsync",
    )
}

fn set_shape(context: *mut c_void, name: &str, shape: &[i64]) -> Result<()> {
    if shape.len() > MAX_DIMS {
        return Err(Error::TooManyDimensions {
            found: shape.len(),
            max: MAX_DIMS,
        });
    }
    let cname = crate::util::to_cstring(name)?;
    trt_check(
        unsafe {
            ffi::trt_context_set_shape(context, cname.as_ptr(), shape.as_ptr(), shape.len() as i32)
        },
        "setInputShape",
    )
}

unsafe fn bind_raw(
    context: *mut c_void,
    io: &[TensorInfo],
    name: &str,
    address: *mut c_void,
    bytes: usize,
) -> Result<()> {
    let info = io
        .iter()
        .find(|info| info.name == name)
        .ok_or_else(|| Error::UnknownTensor {
            name: name.to_string(),
            available: io.iter().map(|info| info.name.clone()).collect(),
        })?;
    if address.is_null() {
        return Err(Error::SizeMismatch {
            tensor: name.to_string(),
            expected: info.size_bytes().unwrap_or(bytes),
            found: 0,
        });
    }
    if let Some(expected) = info.size_bytes() {
        if expected != bytes {
            return Err(Error::SizeMismatch {
                tensor: name.to_string(),
                expected,
                found: bytes,
            });
        }
    }
    let cname = crate::util::to_cstring(name)?;
    trt_check(
        unsafe { ffi::trt_context_bind(context, cname.as_ptr(), address as *const c_void) },
        "setTensorAddress",
    )
}

fn enqueue(context: *mut c_void, stream: &Stream) -> Result<()> {
    trt_check(
        unsafe { ffi::trt_context_enqueue(context, stream.as_raw()) },
        "enqueueV3",
    )
}

fn run(context: *mut c_void, stream: &Stream) -> Result<()> {
    enqueue(context, stream)?;
    stream.synchronize()
}

fn collect_io(engine: *mut c_void) -> Result<Vec<TensorInfo>> {
    let count = unsafe { ffi::trt_engine_num_io(engine) };
    let mut out = Vec::with_capacity(count.max(0) as usize);
    let mut dims = [0i64; MAX_DIMS];
    for index in 0..count {
        let raw_name = unsafe { ffi::trt_engine_io_name(engine, index) };
        if raw_name.is_null() {
            return Err(Error::TensorRt {
                call: "getIOTensorName",
                message: last_message(),
            });
        }
        let name = unsafe { CStr::from_ptr(raw_name) }
            .to_string_lossy()
            .into_owned();
        let mode_code = unsafe { ffi::trt_engine_io_mode(engine, raw_name) };
        let mode = match mode_code {
            0 => IoMode::Internal,
            1 => IoMode::Input,
            2 => IoMode::Output,
            _ => {
                return Err(Error::TensorRt {
                    call: "getTensorIOMode",
                    message: format!("{name}: unknown io mode {mode_code}"),
                })
            }
        };
        let dtype_code = unsafe { ffi::trt_engine_io_dtype(engine, raw_name) };
        let dtype = DataType::from_code(dtype_code).ok_or(Error::UnsupportedDataType {
            tensor: name.clone(),
            code: dtype_code,
        })?;
        let count_dims = unsafe {
            ffi::trt_engine_io_dims(engine, raw_name, dims.as_mut_ptr(), MAX_DIMS as i32)
        };
        if count_dims < 0 {
            return Err(Error::TensorRt {
                call: "getTensorShape",
                message: last_message(),
            });
        }
        out.push(TensorInfo {
            name,
            mode,
            dtype,
            shape: dims[..count_dims as usize].to_vec(),
        });
    }
    Ok(out)
}