Skip to content

Commit 9975d23

Browse files
authored
feat: add RuntimeConfig, RuntimeCache (#101)
* feat: add RuntimeConfig, RuntimeCache * docs: fix doc comment issues
1 parent 727933b commit 9975d23

11 files changed

Lines changed: 329 additions & 18 deletions

File tree

trtexec-rs/src/cli.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ pub struct Args {
5353
#[arg(short, long)]
5454
/// Capture TensorRT API usage to JSON for possible later replay
5555
///
56-
/// See https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/inference-library/capture-replay.html#capture-replay
56+
/// See <https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/inference-library/capture-replay.html#capture-replay>
5757
pub api_capture: Option<PathBuf>,
5858

5959
/// Report layer time

trtx-sys/build.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,11 @@ fn prepare_transformed_headers(header_dir: &Path, out_dir: &Path) -> PathBuf {
100100
+ r#"
101101
namespace nvinfer1 {
102102
class IMoELayer;
103+
class IRuntimeCache;
103104
class IDistCollectiveLayer;
104105
enum class ComputeCapability : int32_t;
106+
enum class CudaGraphStrategy : int32_t;
107+
enum class DynamicShapesKernelSpecializationStrategy : int32_t;
105108
}"#;
106109

107110
// trimming of indentation is necessary, so that rustdoc doesn't interpret

trtx-sys/src/lib.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ better_enum!(HardwareCompatibilityLevel);
6565
better_enum!(RuntimePlatform);
6666
better_enum!(TilingOptimizationLevel);
6767
#[cfg(not(feature = "enterprise"))]
68+
better_enum!(CudaGraphStrategy);
69+
#[cfg(not(feature = "enterprise"))]
70+
better_enum!(DynamicShapesKernelSpecializationStrategy);
71+
better_enum!(ExecutionContextAllocationStrategy);
72+
#[cfg(not(feature = "enterprise"))]
6873
better_enum!(ComputeCapability);
6974
better_enum!(CumulativeOperation);
7075
better_enum!(ElementWiseOperation);
@@ -187,11 +192,10 @@ include_cpp! {
187192
generate!("nvinfer1::IAttention")
188193
generate!("nvinfer1::IMoELayer")
189194
generate!("nvinfer1::IDistCollectiveLayer")
190-
// NOTE: IRNNv2Layer is deprecated (TRT_DEPRECATED) and autocxx cannot generate bindings for it
191-
// RNN operations (lstm, lstmCell, gru, gruCell) remain deferred until we can work around this
192-
// generate!("nvinfer1::IRNNv2Layer")
193195

194196
generate!("nvinfer1::IRuntime")
197+
generate!("nvinfer1::IRuntimeConfig")
198+
generate!("nvinfer1::IRuntimeCache")
195199
generate!("nvinfer1::ICudaEngine")
196200
generate!("nvinfer1::IExecutionContext")
197201
generate!("nvinfer1::IEngineInspector")
@@ -232,11 +236,10 @@ include_cpp! {
232236
generate_pod!("nvinfer1::TilingOptimizationLevel")
233237
generate_pod!("nvinfer1::ComputeCapability")
234238
generate_pod!("nvinfer1::APILanguage")
235-
// NOTE: RNN enums commented out because IRNNv2Layer (deprecated) cannot be generated
236-
// generate!("nvinfer1::RNNOperation")
237-
// generate!("nvinfer1::RNNDirection")
238-
// generate!("nvinfer1::RNNInputMode")
239-
// generate!("nvinfer1::RNNGateType")
239+
generate_pod!("nvinfer1::CudaGraphStrategy")
240+
generate_pod!("nvinfer1::DynamicShapesKernelSpecializationStrategy")
241+
generate_pod!("nvinfer1::ExecutionContextAllocationStrategy")
242+
240243
generate_pod!("nvinfer1::Weights")
241244
generate_pod!("nvinfer1::Permutation")
242245
generate_pod!("nvinfer1::TripLimit")

trtx/src/builder.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,12 @@ impl<'builder> Builder<'builder> {
114114
}
115115
}
116116

117+
/// See [IBuilder::createBuilderConfig]
118+
pub fn create_builder_config(&'_ mut self) -> Result<BuilderConfig<'builder>> {
119+
self.create_config()
120+
}
121+
122+
/// See [IBuilder::createBuilderConfig]
117123
pub fn create_config(&'_ mut self) -> Result<BuilderConfig<'builder>> {
118124
#[cfg(not(feature = "mock"))]
119125
let config_ptr = self.inner.pin_mut().createBuilderConfig();

trtx/src/cuda_engine.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::{ffi::CStr, marker::PhantomData};
88
use crate::engine_inspector::EngineInspector;
99
use crate::error::PropertySetAttempt;
1010
use crate::host_memory::HostMemory;
11+
use crate::runtime_config::RuntimeConfig;
1112
use crate::{DataType, Error, ExecutionContext, Result};
1213
use autocxx::cxx::UniquePtr;
1314
use trtx_sys::{
@@ -34,7 +35,7 @@ impl SerializationConfig<'_> {
3435
pub fn flag(&self, flag: SerializationFlag) -> bool {
3536
self.inner.getFlag(flag.into())
3637
}
37-
/// See [nvinfer1::SerializationConfig::getFlags]
38+
/// See [nvinfer1::ISerializationConfig::getFlags]
3839
pub fn flags(&self) -> u32 {
3940
self.inner.getFlags()
4041
}
@@ -354,6 +355,26 @@ impl<'engine> CudaEngine<'engine> {
354355
Ok(unsafe { ExecutionContext::from_ptr(std::ptr::null_mut())? })
355356
}
356357

358+
/// See [nvinfer1::ICudaEngine::createExecutionContext1]
359+
pub fn create_execution_context_with_config(
360+
&'_ mut self,
361+
runtime_conifg: &'engine RuntimeConfig<'engine>,
362+
) -> Result<ExecutionContext<'engine>> {
363+
#[cfg(not(feature = "mock_runtime"))]
364+
{
365+
use crate::ExecutionContext;
366+
367+
let context_ptr = unsafe {
368+
self.inner
369+
.pin_mut()
370+
.createExecutionContext1(runtime_conifg.inner.as_mut_ptr())
371+
};
372+
Ok(unsafe { ExecutionContext::from_ptr(context_ptr)? })
373+
}
374+
#[cfg(feature = "mock_runtime")]
375+
Ok(unsafe { ExecutionContext::from_ptr(std::ptr::null_mut())? })
376+
}
377+
357378
/// See [nvinfer1::ICudaEngine::createSerializationConfig]
358379
pub fn create_serialization_config(&mut self) -> Result<SerializationConfig<'engine>> {
359380
let config = unsafe {
@@ -395,6 +416,15 @@ impl<'engine> CudaEngine<'engine> {
395416
Ok(unsafe { self.inner.isShapeInferenceIO(name_cstr.as_ptr()) })
396417
}
397418

419+
/// See [nvinfer1::ICudaEngine::createRuntimeConfig]
420+
pub fn create_runtime_config(&'_ mut self) -> Result<RuntimeConfig<'engine>> {
421+
#[cfg(not(feature = "mock"))]
422+
let config_ptr = self.inner.pin_mut().createRuntimeConfig();
423+
#[cfg(feature = "mock")]
424+
let config_ptr = std::ptr::null_mut();
425+
RuntimeConfig::new(config_ptr)
426+
}
427+
398428
/// Returns an iterator over all IO tensor names.
399429
pub fn io_tensor_names(&self) -> Result<CudaEngineIoTensorNamesIter<'_>> {
400430
Ok(CudaEngineIoTensorNamesIter {

trtx/src/error.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ pub enum PropertySetAttempt {
2222
ExecutionContextTensorDebugState,
2323
ExecutionContextNcclCommunicator,
2424
ExecutionContextInputShape,
25+
RuntimeConfigCudaGraphStrategy,
26+
RuntimeConfigRuntimeCache,
27+
RuntimeCacheDeserialize,
2528
DequantizeLayerBlockShape,
2629
QuantizeLayerBlockShape,
2730
AttentionLayerInput,
@@ -112,6 +115,12 @@ pub enum Error {
112115
#[error("Failed to create BuilderConfig")]
113116
BuilderConfigCreationFailed,
114117

118+
#[error("Failed to create RuntimeConfig")]
119+
RuntimeConfigCreationFailed,
120+
121+
#[error("Failed to create RuntimeCache")]
122+
RuntimeCacheCreationFailed,
123+
115124
#[error("Failed to set property: {0:?}")]
116125
FailedToSetProperty(PropertySetAttempt),
117126

@@ -132,6 +141,9 @@ pub enum Error {
132141

133142
#[error("Failed to set IO tensor address for tensor {tensor_name:?}")]
134143
FailedToSetTensorAddress { tensor_name: String },
144+
145+
#[error("Failed to reset to RuntimeCache")]
146+
FailedToResetRuntimeCache,
135147
}
136148

137149
impl<T> From<std::sync::PoisonError<T>> for Error {

trtx/src/execution_context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::interfaces::{
1414
/// [`trtx_sys::nvinfer1::IExecutionContext`] — C++ [`nvinfer1::IExecutionContext`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_execution_context.html).
1515
///
1616
/// `inner` is declared last so it is dropped first (see [`Drop`]): TensorRT must release
17-
/// [`DebugListener`](crate::interfaces::DebugListener) / [`Profiler`](crate::interfaces::Profiler)
17+
/// [DebugListener] / [Profiler]
1818
/// pointers before their Rust wrappers run destructors.
1919
pub struct ExecutionContext<'a> {
2020
_engine: std::marker::PhantomData<&'a CudaEngine<'a>>,

trtx/src/lib.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ pub mod onnx_parser;
151151
pub mod optimization_profile;
152152
pub mod refitter;
153153
pub mod runtime;
154+
#[cfg(not(feature = "enterprise"))]
155+
pub mod runtime_cache;
156+
pub mod runtime_config;
154157
pub mod tensor;
155158

156159
// Re-export commonly used types
@@ -169,7 +172,9 @@ pub use network::{ConvWeights, NetworkDefinition, OwnedConvWeights, OwnedWeights
169172
#[cfg(feature = "onnxparser")]
170173
pub use onnx_parser::OnnxParser;
171174
pub use refitter::Refitter;
172-
pub use runtime::{CudaEngine, EngineInspector, ExecutionContext, Runtime};
175+
#[cfg(not(feature = "enterprise"))]
176+
pub use runtime::RuntimeCache;
177+
pub use runtime::{CudaEngine, EngineInspector, ExecutionContext, Runtime, RuntimeConfig};
173178

174179
#[cfg(feature = "dlopen_tensorrt_rtx")]
175180
#[cfg(not(any(feature = "link_tensorrt_rtx", feature = "mock")))]
@@ -303,12 +308,14 @@ pub fn dynamically_load_tensorrt_onnxparser(_filename: Option<impl AsFilename>)
303308

304309
// Re-export TensorRT enums
305310
pub use trtx_sys::{
306-
ActivationType, CumulativeOperation, DataType, ElementWiseOperation, GatherMode,
307-
InterpolationMode, LayerInformationFormat, LayerType, MatrixOperation, PaddingMode,
308-
PoolingType, ReduceOperation, ResizeCoordinateTransformation, ResizeMode, ResizeRoundMode,
309-
ResizeSelector, SampleMode, ScaleMode, ScatterMode, TensorFormat, TensorIOMode, TopKOperation,
310-
UnaryOperation,
311+
ActivationType, CumulativeOperation, DataType, ElementWiseOperation,
312+
ExecutionContextAllocationStrategy, GatherMode, InterpolationMode, LayerInformationFormat,
313+
LayerType, MatrixOperation, PaddingMode, PoolingType, ReduceOperation,
314+
ResizeCoordinateTransformation, ResizeMode, ResizeRoundMode, ResizeSelector, SampleMode,
315+
ScaleMode, ScatterMode, TensorFormat, TensorIOMode, TopKOperation, UnaryOperation,
311316
};
312317

313318
#[cfg(not(feature = "enterprise"))]
314-
pub use trtx_sys::ComputeCapability;
319+
pub use trtx_sys::{
320+
ComputeCapability, CudaGraphStrategy, DynamicShapesKernelSpecializationStrategy,
321+
};

trtx/src/runtime.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ pub use crate::engine_inspector::EngineInspector;
1414
use crate::error::{Error, Result};
1515
pub use crate::execution_context::ExecutionContext;
1616
use crate::logger::Logger;
17+
#[cfg(not(feature = "enterprise"))]
18+
pub use crate::runtime_cache::RuntimeCache;
19+
pub use crate::runtime_config::RuntimeConfig;
1720

1821
/// [`trtx_sys::nvinfer1::IRuntime`] — C++ [`nvinfer1::IRuntime`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_runtime.html).
1922
pub struct Runtime<'logger> {

trtx/src/runtime_cache.rs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
//! Runtime cache for TensorRT JIT compilation (serialize / deserialize).
2+
//!
3+
//! [`RuntimeCache`] wraps [`trtx_sys::nvinfer1::IRuntimeCache`] (C++ [`nvinfer1::IRuntimeCache`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_runtime_cache.html).
4+
5+
use std::marker::PhantomData;
6+
7+
use crate::error::{PropertySetAttempt, Result};
8+
use crate::host_memory::HostMemory;
9+
use crate::Error;
10+
use cxx::UniquePtr;
11+
use trtx_sys::nvinfer1::{self, IRuntimeCache};
12+
13+
/// [`trtx_sys::nvinfer1::IRuntimeCache`] — C++ [`nvinfer1::IRuntimeCache`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_runtime_cache.html).
14+
pub struct RuntimeCache<'engine> {
15+
pub(crate) inner: UniquePtr<IRuntimeCache>,
16+
_engine: PhantomData<&'engine nvinfer1::ICudaEngine>,
17+
}
18+
19+
impl std::fmt::Debug for RuntimeCache<'_> {
20+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21+
f.debug_struct("RuntimeCache")
22+
.field("inner", &format!("{:x}", self.inner.as_ptr() as usize))
23+
.finish_non_exhaustive()
24+
}
25+
}
26+
27+
impl<'engine> RuntimeCache<'engine> {
28+
pub(crate) fn new(cache: *mut nvinfer1::IRuntimeCache) -> Result<Self> {
29+
#[cfg(not(feature = "mock"))]
30+
if cache.is_null() {
31+
return Err(Error::RuntimeCacheCreationFailed);
32+
}
33+
Ok(Self {
34+
inner: unsafe { UniquePtr::from_raw(cache) },
35+
_engine: Default::default(),
36+
})
37+
}
38+
39+
/// See [IRuntimeCache::serialize].
40+
pub fn serialize(&self) -> Result<HostMemory<'engine>> {
41+
#[cfg(not(feature = "mock"))]
42+
{
43+
let host_mem = unsafe { self.inner.serialize().as_mut() }
44+
.ok_or_else(|| Error::Runtime("Failed to serialize IRuntimeCache".to_string()))?;
45+
Ok(unsafe { HostMemory::from_raw(host_mem) })
46+
}
47+
#[cfg(feature = "mock")]
48+
Ok(unsafe { HostMemory::from_raw(std::ptr::null_mut()) })
49+
}
50+
51+
/// See [IRuntimeCache::deserialize].
52+
pub fn deserialize(&mut self, blob: &[u8]) -> Result<()> {
53+
if cfg!(not(feature = "mock")) {
54+
if unsafe {
55+
self.inner
56+
.pin_mut()
57+
.deserialize(blob.as_ptr() as *const autocxx::c_void, blob.len())
58+
} {
59+
Ok(())
60+
} else {
61+
Err(Error::FailedToSetProperty(
62+
PropertySetAttempt::RuntimeCacheDeserialize,
63+
))
64+
}
65+
} else {
66+
Ok(())
67+
}
68+
}
69+
70+
/// See [IRuntimeCache::reset].
71+
pub fn reset(&mut self) -> Result<()> {
72+
if cfg!(not(feature = "mock")) {
73+
if self.inner.pin_mut().reset() {
74+
Ok(())
75+
} else {
76+
Err(Error::FailedToResetRuntimeCache)
77+
}
78+
} else {
79+
Ok(())
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)