Skip to content

πŸ“„ Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

feat(inference_engine): add TensorRT engine support (#623)

locviettrib132a915e714
diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yaml
index 7f3c019..199d57a 100644
--- a/python/rapidocr/config.yaml
+++ b/python/rapidocr/config.yaml
@@ -81,6 +81,32 @@ EngineConfig:
npu_ep_cfg:
device_id: 0
+ tensorrt:
+ device_id: 0
+ use_fp16: true
+ use_int8: false
+ workspace_size: 1073741824 # 1GB = 1 << 30
+
+ # Engine caching
+ cache_dir: null # null = use default models dir
+ force_rebuild: false
+
+ # Dynamic shape optimization profiles
+ det_profile:
+ min_shape: [1, 3, 32, 32]
+ opt_shape: [1, 3, 736, 736]
+ max_shape: [1, 3, 2048, 2048]
+
+ rec_profile:
+ min_shape: [1, 3, 48, 32]
+ opt_shape: [6, 3, 48, 320]
+ max_shape: [6, 3, 48, 2048]
+
+ cls_profile:
+ min_shape: [1, 3, 48, 32]
+ opt_shape: [6, 3, 48, 192]
+ max_shape: [6, 3, 48, 192]
+
mnn: {}
Det:
diff --git a/python/rapidocr/inference_engine/base.py b/python/rapidocr/inference_engine/base.py
index aacb79a..6bf6ca7 100644
--- a/python/rapidocr/inference_engine/base.py
+++ b/python/rapidocr/inference_engine/base.py
@@ -53,6 +53,14 @@ def get_engine(engine_type: EngineType):
return TorchInferSession
+ if engine_type == EngineType.TENSORRT:
+ if not import_package("tensorrt"):
+ raise ImportError("tensorrt is not installed")
+
+ from .tensorrt import TRTInferSession
+
+ return TRTInferSession
+
if engine_type == EngineType.MNN:
if not import_package("MNN"):
raise ImportError("MNN is not installed")
diff --git a/python/rapidocr/inference_engine/tensorrt/__init__.py b/python/rapidocr/inference_engine/tensorrt/__init__.py
new file mode 100644
index 0000000..54b9166
--- /dev/null
+++ b/python/rapidocr/inference_engine/tensorrt/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .main import TRTInferSession
diff --git a/python/rapidocr/inference_engine/tensorrt/engine_builder.py b/python/rapidocr/inference_engine/tensorrt/engine_builder.py
new file mode 100644
index 0000000..d89c240
--- /dev/null
+++ b/python/rapidocr/inference_engine/tensorrt/engine_builder.py
@@ -0,0 +1,122 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+from typing import Any, Dict
+
+import tensorrt as trt
+
+from ...utils.log import logger
+
+
+class TRTEngineBuilder:
+ """Build TensorRT engine from ONNX model"""
+
+ def __init__(
+ self,
+ onnx_path: Path,
+ engine_path: Path,
+ cfg: Dict[str, Any],
+ task_type: str,
+ trt_logger: trt.Logger,
+ ):
+ self.onnx_path = onnx_path
+ self.engine_path = engine_path
+ self.cfg = cfg
+ self.task_type = task_type
+ self.trt_logger = trt_logger
+
+ def build(self) -> trt.ICudaEngine:
+ """Build TensorRT engine from ONNX"""
+ builder = trt.Builder(self.trt_logger)
+ network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
+ network = builder.create_network(network_flags)
+ parser = trt.OnnxParser(network, self.trt_logger)
+
+ # Parse ONNX model
+ with open(self.onnx_path, "rb") as f:
+ if not parser.parse(f.read()):
+ for i in range(parser.num_errors):
+ logger.error(f"ONNX parse error: {parser.get_error(i)}")
+ raise RuntimeError("Failed to parse ONNX model")
+
+ # Configure builder
+ config = builder.create_builder_config()
+
+ # Set workspace size
+ workspace_size = self.cfg.get("workspace_size", 1 << 30) # 1GB default
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_size)
+
+ # Set precision
+ if self.cfg.get("use_fp16", True) and builder.platform_has_fast_fp16:
+ config.set_flag(trt.BuilderFlag.FP16)
+ logger.info("Using FP16 precision")
+ else:
+ logger.info("Using FP32 precision")
+
+ if self.cfg.get("use_int8", False) and builder.platform_has_fast_int8:
+ config.set_flag(trt.BuilderFlag.INT8)
+ logger.info("Using INT8 precision")
+
+ # Add optimization profile for dynamic shapes
+ profile = builder.create_optimization_profile()
+ self._set_dynamic_shapes(network, profile)
+ config.add_optimization_profile(profile)
+
+ # Build engine
+ logger.info("Building TensorRT engine (this may take a few minutes)...")
+ serialized_engine = builder.build_serialized_network(network, config)
+
+ if serialized_engine is None:
+ raise RuntimeError("Failed to build TensorRT engine")
+
+ # Save engine to cache
+ self.engine_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(self.engine_path, "wb") as f:
+ f.write(serialized_engine)
+ logger.info(f"TensorRT engine saved to {self.engine_path}")
+
+ # Deserialize and return
+ runtime = trt.Runtime(self.trt_logger)
+ return runtime.deserialize_cuda_engine(serialized_engine)
+
+ def _set_dynamic_shapes(
+ self, network: trt.INetworkDefinition, profile: trt.IOptimizationProfile
+ ):
+ """Set dynamic shape optimization profiles"""
+ profile_key = f"{self.task_type}_profile"
+ profile_cfg = self.cfg.get(profile_key, {})
+
+ # Default profiles based on task type
+ if self.task_type == "det":
+ min_shape = profile_cfg.get("min_shape", (1, 3, 32, 32))
+ opt_shape = profile_cfg.get("opt_shape", (1, 3, 736, 736))
+ max_shape = profile_cfg.get("max_shape", (1, 3, 2048, 2048))
+ elif self.task_type == "rec":
+ min_shape = profile_cfg.get("min_shape", (1, 3, 48, 32))
+ opt_shape = profile_cfg.get("opt_shape", (6, 3, 48, 320))
+ max_shape = profile_cfg.get("max_shape", (6, 3, 48, 2048))
+ elif self.task_type == "cls":
+ min_shape = profile_cfg.get("min_shape", (1, 3, 48, 32))
+ opt_shape = profile_cfg.get("opt_shape", (6, 3, 48, 192))
+ max_shape = profile_cfg.get("max_shape", (6, 3, 48, 192))
+ else:
+ # Generic fallback
+ min_shape = (1, 3, 32, 32)
+ opt_shape = (1, 3, 224, 224)
+ max_shape = (1, 3, 2048, 2048)
+
+ # Set shapes for input tensor
+ input_tensor = network.get_input(0)
+ input_name = input_tensor.name
+
+ profile.set_shape(
+ input_name,
+ min=tuple(min_shape),
+ opt=tuple(opt_shape),
+ max=tuple(max_shape),
+ )
+ logger.info(
+ f"Set optimization profile for {input_name}: "
+ f"min={min_shape}, opt={opt_shape}, max={max_shape}"
+ )
diff --git a/python/rapidocr/inference_engine/tensorrt/main.py b/python/rapidocr/inference_engine/tensorrt/main.py
new file mode 100644
index 0000000..6b636a7
--- /dev/null
+++ b/python/rapidocr/inference_engine/tensorrt/main.py
@@ -0,0 +1,618 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+"""
+TensorRT Inference Session for RapidOCR.
+
+This module provides TensorRT-based inference for OCR models, offering
+significant performance improvements over ONNX Runtime on NVIDIA GPUs.
+
+Key Features:
+- Automatic engine building and caching
+- Dynamic shape support via optimization profiles
+- Pre-allocated buffers for minimal inference overhead
+- Optional pinned memory for faster data transfers
+
+Performance Optimizations:
+1. Pre-allocated buffers with max shape (avoids reallocation overhead)
+2. Pinned memory for faster CPU-GPU transfers (~2x on discrete GPUs)
+3. Persistent CUDA stream (no stream creation per inference)
+4. Async memory copies overlapped with computation
+
+Example:
+ >>> from rapidocr.inference_engine.tensorrt import TRTInferSession
+ >>> with TRTInferSession(config) as session:
+ ... output = session(input_array)
+"""
+import traceback
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+import numpy as np
+from cuda.bindings import runtime as cudart
+import tensorrt as trt
+
+from ...utils.download_file import DownloadFile, DownloadFileInput
+from ...utils.log import logger
+from ...utils.typings import EngineType
+from ..base import FileInfo, InferSession
+from .engine_builder import TRTEngineBuilder
+from .memory_utils import allocate_buffers, free_buffers
+
+
+class TRTInferSession(InferSession):
+ """TensorRT Inference Session for RapidOCR.
+
+ This class provides GPU-accelerated inference using NVIDIA TensorRT.
+ It manages engine loading/building, memory allocation, and inference
+ execution with optimizations for minimal latency.
+
+ Supports context manager protocol for automatic resource cleanup:
+ >>> with TRTInferSession(cfg) as session:
+ ... result = session(input_data)
+
+ Attributes:
+ cfg: Configuration dictionary.
+ engine: TensorRT engine instance.
+ context: TensorRT execution context.
+ stream: CUDA stream for async operations.
+ inputs: List of input buffer objects.
+ outputs: List of output buffer objects.
+ """
+
+ def __init__(self, cfg: Dict[str, Any]):
+ """Initialize TensorRT inference session.
+
+ Args:
+ cfg: Configuration dictionary containing:
+ - engine_cfg: TensorRT-specific settings (device_id, precision, etc.)
+ - model_path: Optional path to custom ONNX model
+ - task_type, lang_type, etc.: For default model selection
+
+ Raises:
+ AssertionError: If CUDA device setup fails.
+ RuntimeError: If engine building fails.
+ """
+ self.cfg = cfg
+ self.engine_cfg = cfg.get("engine_cfg", {})
+ self._closed = False
+
+ # Initialize CUDA device
+ self.device_id = self._setup_cuda_device()
+
+ # TensorRT logger
+ self.trt_logger = trt.Logger(trt.Logger.WARNING)
+
+ # Get or build engine
+ engine_path = self._get_engine_path(cfg)
+ self.engine = self._load_or_build_engine(cfg, engine_path)
+
+ # Create execution context
+ self.context = self.engine.create_execution_context()
+
+ # Allocate memory buffers (pre-allocated with max shape)
+ self.inputs, self.outputs, self.bindings, self.stream = allocate_buffers(
+ self.engine, self.context
+ )
+
+ logger.info(f"TensorRT engine loaded: {engine_path}")
+
+ # Detect MULTI model for square input requirement
+ self._requires_square_input = self._check_multi_model(cfg)
+ if self._requires_square_input:
+ self._max_square_size = self._get_max_profile_size()
+ logger.debug(f"MULTI det model: requires square input, max_size={self._max_square_size}")
+ else:
+ self._requires_square_input = False
+ self._max_square_size = 2048
+
+ # =========================================================================
+ # Context Manager Protocol
+ # =========================================================================
+
+ def __enter__(self) -> "TRTInferSession":
+ """Enter context manager.
+
+ Returns:
+ self: The session instance.
+ """
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
+ """Exit context manager and cleanup resources.
+
+ Args:
+ exc_type: Exception type if an exception occurred.
+ exc_val: Exception value if an exception occurred.
+ exc_tb: Exception traceback if an exception occurred.
+ """
+ self.close()
+
+ def close(self) -> None:
+ """Explicitly close and cleanup resources.
+
+ This method releases all CUDA resources including:
+ - GPU memory buffers
+ - CUDA stream
+ - TensorRT context and engine
+
+ Safe to call multiple times.
+
+ Example:
+ >>> session = TRTInferSession(cfg)
+ >>> try:
+ ... result = session(data)
+ ... finally:
+ ... session.close()
+ """
+ if self._closed:
+ return
+
+ self._closed = True
+
+ try:
+ # Synchronize stream before cleanup
+ if hasattr(self, "stream") and self.stream is not None:
+ try:
+ cudart.cudaStreamSynchronize(self.stream)
+ except Exception as e:
+ logger.debug(f"Stream sync error during close: {e}")
+
+ # Free GPU memory buffers
+ if hasattr(self, "inputs") and hasattr(self, "outputs"):
+ try:
+ free_buffers(self.inputs, self.outputs, self.stream)
+ except Exception as e:
+ logger.debug(f"Buffer free error during close: {e}")
+
+ # Destroy CUDA stream
+ if hasattr(self, "stream") and self.stream is not None:
+ try:
+ cudart.cudaStreamDestroy(self.stream)
+ except Exception as e:
+ logger.debug(f"Stream destroy error during close: {e}")
+
+ except Exception as e:
+ logger.debug(f"Error during session close: {e}")
+
+ def __del__(self):
+ """Destructor - cleanup resources if not already closed."""
+ self.close()
+
+ # =========================================================================
+ # Inference Methods
+ # =========================================================================
+
+ def __call__(self, input_content: np.ndarray) -> np.ndarray:
+ """Run inference on input data.
+
+ This method executes the TensorRT engine on the provided input.
+ It uses pre-allocated buffers to avoid memory allocation overhead.
+
+ Args:
+ input_content: Input numpy array with shape matching the model.
+ For detection: (N, C, H, W)
+ For recognition: (N, C, H, W)
+
+ Returns:
+ Output numpy array from the model.
+
+ Raises:
+ TensorRTError: If inference fails.
+
+ Example:
+ >>> input_data = np.random.randn(1, 3, 224, 224).astype(np.float32)
+ >>> output = session(input_data)
+ """
+ try:
+ # Step 1: Handle square input for MULTI model
+ original_hw = None
+ if self._requires_square_input:
+ input_content, original_hw = self._pad_to_square(input_content)
+
+ # Step 2: Set input shape for dynamic dimensions
+ output_shape = self._set_input_shape(input_content)
+
+ # Step 3: Copy input data to GPU
+ self._copy_input_to_device(input_content)
+
+ # Step 4: Execute inference
+ self._execute_inference()
+
+ # Step 5: Copy output back to CPU
+ output = self._copy_output_to_host(output_shape)
+
+ # Step 6: Crop output back to original shape
+ if original_hw is not None:
+ output = self._crop_output(output, original_hw)
+
+ return output
+
+ except Exception as e:
+ error_info = traceback.format_exc()
+ raise TensorRTError(
+ f"Inference failed for input shape {input_content.shape}:\n{error_info}"
+ ) from e
+
+ def _set_input_shape(self, input_content: np.ndarray) -> tuple:
+ """Set input shape and get corresponding output shape.
+
+ For dynamic shape networks, we need to inform TensorRT of the
+ actual input shape before each inference.
+
+ Args:
+ input_content: Input array to get shape from.
+
+ Returns:
+ Output shape tuple after setting input shape.
+ """
+ input_name = self.engine.get_tensor_name(0)
+ self.context.set_input_shape(input_name, input_content.shape)
+
+ output_name = self.engine.get_tensor_name(1)
+ return self.context.get_tensor_shape(output_name)
+
+ def _copy_input_to_device(self, input_content: np.ndarray) -> None:
+ """Copy input data to GPU asynchronously.
+
+ Uses pre-allocated pinned memory buffer for optimal transfer speed.
+
+ Args:
+ input_content: Input data to copy.
+ """
+ input_flat = input_content.ravel()
+ self.inputs[0].host[: input_flat.size] = input_flat
+
+ cudart.cudaMemcpyAsync(
+ self.inputs[0].device,
+ self.inputs[0].host.ctypes.data,
+ input_flat.nbytes,
+ cudart.cudaMemcpyKind.cudaMemcpyHostToDevice,
+ self.stream,
+ )
+
+ def _execute_inference(self) -> None:
+ """Execute TensorRT inference asynchronously."""
+ self.context.execute_async_v3(stream_handle=self.stream)
+
+ def _copy_output_to_host(self, output_shape: tuple) -> np.ndarray:
+ """Copy output from GPU to CPU and reshape.
+
+ Only copies the actual output size, not the full pre-allocated buffer.
+
+ Args:
+ output_shape: Expected output shape.
+
+ Returns:
+ Output array reshaped to correct dimensions.
+ """
+ output_size = int(np.prod(output_shape))
+ output_nbytes = output_size * self.outputs[0].host.itemsize
+
+ cudart.cudaMemcpyAsync(
+ self.outputs[0].host.ctypes.data,
+ self.outputs[0].device,
+ output_nbytes,
+ cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost,
+ self.stream,
+ )
+
+ # Wait for all async operations to complete
+ cudart.cudaStreamSynchronize(self.stream)
+
+ return self.outputs[0].host[:output_size].reshape(output_shape)
+
+ # =========================================================================
+ # MULTI Model Square Input Handling
+ # =========================================================================
+
+ def _check_multi_model(self, cfg: Dict[str, Any]) -> bool:
+ """Check if this is MULTI detection model requiring square input.
+
+ Args:
+ cfg: Configuration dictionary.
+
+ Returns:
+ True if this is MULTI detection model, False otherwise.
+ """
+ try:
+ from ...utils.typings import LangDet, TaskType
+ is_det = getattr(cfg, 'task_type', None) == TaskType.DET
+ is_multi = getattr(cfg, 'lang_type', None) == LangDet.MULTI
+ return is_det and is_multi
+ except Exception:
+ return False
+
+ def _get_max_profile_size(self) -> int:
+ """Get maximum dimension from TensorRT optimization profile.
+
+ Returns:
+ Maximum height/width allowed by the optimization profile.
+ """
+ try:
+ # Try to get from config first
+ profile_cfg = self.engine_cfg.get("det_profile", {})
+ max_shape = profile_cfg.get("max_shape")
+ if max_shape and len(max_shape) >= 4:
+ return max(max_shape[2], max_shape[3]) # max(H, W)
+
+ # Fallback: query from engine
+ input_name = self.engine.get_tensor_name(0)
+ profile_shape = self.engine.get_tensor_profile_shape(input_name, 0)
+ if profile_shape and len(profile_shape) >= 3:
+ max_shape = profile_shape[2] # Index 2 = max shape
+ return max(max_shape[2], max_shape[3])
+ except Exception as e:
+ logger.debug(f"Could not get max profile size: {e}")
+
+ # Default fallback
+ return 2048
+
+ def _pad_to_square(self, input_content: np.ndarray) -> tuple:
+ """Pad input to square shape for MULTI model.
+
+ Args:
+ input_content: Input array with shape (N, C, H, W).
+
+ Returns:
+ Tuple of (padded_input, original_hw) where:
+ - padded_input: Square input array (N, C, S, S)
+ - original_hw: Original (H, W) for later cropping, or None if already square
+ """
+ N, C, H, W = input_content.shape
+
+ if H == W:
+ return input_content, None # Already square
+
+ # Calculate square size
+ square_size = max(H, W)
+
+ # Limit to max profile size if needed
+ if square_size > self._max_square_size:
+ logger.warning(
+ f"Square size {square_size} exceeds max profile size {self._max_square_size}. "
+ f"Limiting to {self._max_square_size}. This may cause accuracy loss."
+ )
+ square_size = self._max_square_size
+
+ # Ensure divisible by 32 (TensorRT requirement)
+ square_size = int(round(square_size / 32) * 32)
+
+ # Create padded array (zero padding)
+ padded = np.zeros((N, C, square_size, square_size), dtype=input_content.dtype)
+
+ # Copy original content to top-left
+ copy_h = min(H, square_size)
+ copy_w = min(W, square_size)
+ padded[:, :, :copy_h, :copy_w] = input_content[:, :, :copy_h, :copy_w]
+
+ return padded, (H, W)
+
+ def _crop_output(self, output: np.ndarray, original_hw: tuple) -> np.ndarray:
+ """Crop output back to original shape after square inference.
+
+ Args:
+ output: Output array with shape (N, C, S, S) from square inference.
+ original_hw: Original (H, W) before padding.
+
+ Returns:
+ Cropped output array with shape (N, C, H, W).
+ """
+ if original_hw is None:
+ return output
+
+ orig_h, orig_w = original_hw
+ out_h, out_w = output.shape[2:4]
+
+ if out_h >= orig_h and out_w >= orig_w:
+ # Normal case: crop to original size
+ return output[:, :, :orig_h, :orig_w]
+ else:
+ # Output is smaller - need to scale
+ # This happens when square_size was limited by max_profile_size
+ scale_h = out_h / max(orig_h, orig_w)
+ scale_w = out_w / max(orig_h, orig_w)
+ crop_h = int(orig_h * scale_h)
+ crop_w = int(orig_w * scale_w)
+ return output[:, :, :crop_h, :crop_w]
+
+ # =========================================================================
+ # Initialization Helpers
+ # =========================================================================
+
+ def _setup_cuda_device(self) -> int:
+ """Setup CUDA device for inference.
+
+ Returns:
+ Device ID that was set.
+
+ Raises:
+ AssertionError: If CUDA device setup fails.
+ """
+ device_id = self.engine_cfg.get("device_id", 0)
+ status_tuple = cudart.cudaSetDevice(device_id)
+ status = status_tuple[0]
+ assert status.value == 0, (
+ f"Failed to set CUDA device {device_id}: {status}. "
+ f"Ensure CUDA is properly installed and GPU is available."
+ )
+ return device_id
+
+ def _get_engine_path(self, cfg: Dict[str, Any]) -> Path:
+ """Determine the TensorRT engine file path.
+
+ Engine files are cached per GPU architecture and precision setting
+ to avoid rebuilding on subsequent runs.
+
+ Args:
+ cfg: Configuration dictionary.
+
+ Returns:
+ Path to engine file (may not exist yet).
+ """
+ cache_dir = self.engine_cfg.get("cache_dir")
+ if cache_dir is None:
+ cache_dir = self.DEFAULT_MODEL_PATH
+
+ cache_dir = Path(cache_dir)
+ cache_dir.mkdir(parents=True, exist_ok=True)
+
+ model_name = self._get_model_name(cfg)
+ gpu_arch = self._get_gpu_arch()
+ precision = "fp16" if self.engine_cfg.get("use_fp16", True) else "fp32"
+
+ return cache_dir / f"{model_name}_{gpu_arch}_{precision}.engine"
+
+ def _get_model_name(self, cfg: Dict[str, Any]) -> str:
+ """Extract model name from config for engine filename."""
+ if cfg.get("model_path"):
+ return Path(cfg["model_path"]).stem
+
+ task_type = cfg.task_type.value
+ lang_type = cfg.lang_type.value
+ ocr_version = cfg.ocr_version.value
+ model_type = cfg.model_type.value
+ return f"{lang_type}_{ocr_version}_{task_type}_{model_type}"
+
+ def _get_gpu_arch(self) -> str:
+ """Get GPU architecture string for cache key (e.g., 'sm87')."""
+ status, major = cudart.cudaDeviceGetAttribute(
+ cudart.cudaDeviceAttr.cudaDevAttrComputeCapabilityMajor, self.device_id
+ )
+ assert status.value == 0, f"Failed to get compute capability: {status}"
+
+ status, minor = cudart.cudaDeviceGetAttribute(
+ cudart.cudaDeviceAttr.cudaDevAttrComputeCapabilityMinor, self.device_id
+ )
+ assert status.value == 0, f"Failed to get compute capability: {status}"
+
+ return f"sm{major}{minor}"
+
+ def _load_or_build_engine(
+ self, cfg: Dict[str, Any], engine_path: Path
+ ) -> trt.ICudaEngine:
+ """Load cached engine or build new one from ONNX.
+
+ Args:
+ cfg: Configuration dictionary.
+ engine_path: Path where engine should be cached.
+
+ Returns:
+ TensorRT engine instance.
+ """
+ force_rebuild = self.engine_cfg.get("force_rebuild", False)
+
+ # Try to load cached engine
+ if engine_path.exists() and not force_rebuild:
+ try:
+ return self._load_engine(engine_path)
+ except Exception as e:
+ logger.warning(
+ f"Failed to load cached engine {engine_path}: {e}. "
+ f"Will rebuild from ONNX."
+ )
+
+ # Build new engine from ONNX
+ onnx_path = self._get_onnx_path(cfg)
+ logger.info(f"Building TensorRT engine from {onnx_path}")
+
+ builder = TRTEngineBuilder(
+ onnx_path=onnx_path,
+ engine_path=engine_path,
+ cfg=self.engine_cfg,
+ task_type=cfg.task_type.value,
+ trt_logger=self.trt_logger,
+ )
+ return builder.build()
+
+ def _get_onnx_path(self, cfg: Dict[str, Any]) -> Path:
+ """Get ONNX model path, downloading if necessary."""
+ model_path = cfg.get("model_path")
+
+ if model_path is None:
+ # Download default ONNX model
+ original_engine_type = cfg.engine_type
+ cfg.engine_type = EngineType.ONNXRUNTIME
+
+ model_info = self.get_model_url(
+ FileInfo(
+ engine_type=EngineType.ONNXRUNTIME,
+ ocr_version=cfg.ocr_version,
+ task_type=cfg.task_type,
+ lang_type=cfg.lang_type,
+ model_type=cfg.model_type,
+ )
+ )
+
+ cfg.engine_type = original_engine_type
+
+ model_path = self.DEFAULT_MODEL_PATH / Path(model_info["model_dir"]).name
+ download_params = DownloadFileInput(
+ file_url=model_info["model_dir"],
+ sha256=model_info["SHA256"],
+ save_path=model_path,
+ logger=logger,
+ )
+ DownloadFile.run(download_params)
+
+ model_path = Path(model_path)
+ self._verify_model(model_path)
+ return model_path
+
+ def _load_engine(self, engine_path: Path) -> trt.ICudaEngine:
+ """Load a serialized TensorRT engine from disk."""
+ runtime = trt.Runtime(self.trt_logger)
+ with open(engine_path, "rb") as f:
+ engine_data = f.read()
+ return runtime.deserialize_cuda_engine(engine_data)
+
+ # =========================================================================
+ # Interface Methods (required by InferSession)
+ # =========================================================================
+
+ def have_key(self, key: str = "character") -> bool:
+ """Check if engine has metadata key.
+
+ TensorRT engines don't store custom metadata like ONNX models.
+
+ Returns:
+ Always False for TensorRT engines.
+ """
+ return False
+
+ @classmethod
+ def get_dict_key_url(cls, file_info: FileInfo) -> Optional[str]:
+ """Get dictionary URL by falling back to Paddle/ONNX model config.
+
+ TensorRT doesn't have entries in default_models.yaml, so we
+ look up the dictionary URL from Paddle or ONNX configurations.
+
+ Args:
+ file_info: Model file information.
+
+ Returns:
+ Dictionary URL string or None if not found.
+ """
+ # Try Paddle first (usually has dict_url)
+ for engine_type in [EngineType.PADDLE, EngineType.ONNXRUNTIME]:
+ try:
+ fallback_info = FileInfo(
+ engine_type=engine_type,
+ ocr_version=file_info.ocr_version,
+ task_type=file_info.task_type,
+ lang_type=file_info.lang_type,
+ model_type=file_info.model_type,
+ )
+ model_dict = cls.get_model_url(fallback_info)
+ if model_dict and "dict_url" in model_dict:
+ return model_dict["dict_url"]
+ except Exception as e:
+ logger.debug(f"Failed to get dict URL from {engine_type.value}: {e}")
+
+ return None
+
+
+class TensorRTError(Exception):
+ """Exception raised for TensorRT inference errors."""
+
+ pass
diff --git a/python/rapidocr/inference_engine/tensorrt/memory_utils.py b/python/rapidocr/inference_engine/tensorrt/memory_utils.py
new file mode 100644
index 0000000..f91041d
--- /dev/null
+++ b/python/rapidocr/inference_engine/tensorrt/memory_utils.py
@@ -0,0 +1,311 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+"""
+TensorRT Memory Utilities for RapidOCR.
+
+This module provides memory management utilities for TensorRT inference,
+including buffer allocation with optional pinned memory support.
+
+Performance Notes:
+- Pre-allocating with MAX shape prevents expensive reallocation during inference
+- Pinned memory provides ~2x faster H2D/D2H transfers on discrete GPUs
+- On Tegra/Jetson (unified memory), pinned memory benefit is less pronounced
+"""
+import ctypes
+from dataclasses import dataclass
+from typing import List, Optional, Tuple
+
+import numpy as np
+from cuda.bindings import runtime as cudart
+import tensorrt as trt
+
+
+# =============================================================================
+# Constants - Replace magic numbers with named constants
+# =============================================================================
+
+# Default maximum shapes for buffer allocation when profile info unavailable
+DEFAULT_MAX_INPUT_SHAPE = (1, 3, 2048, 2048) # Max for detection input
+DEFAULT_MAX_OUTPUT_SHAPE = (1, 2048, 2048) # Generous output buffer
+
+# NumPy dtype to ctypes mapping for pinned memory allocation
+_NUMPY_TO_CTYPE = {
+ np.float32: ctypes.c_float,
+ np.float16: ctypes.c_uint16, # No native half in ctypes
+ np.int32: ctypes.c_int32,
+ np.int64: ctypes.c_int64,
+ np.int8: ctypes.c_int8,
+ np.uint8: ctypes.c_uint8,
+}
+
+
+# =============================================================================
+# Data Classes
+# =============================================================================
+
+
+@dataclass
+class HostDeviceMemory:
+ """Host and device memory pair for TensorRT inference.
+
+ This class holds paired CPU (host) and GPU (device) memory buffers
+ used for input/output data transfer during TensorRT inference.
+
+ Attributes:
+ host: NumPy array for host memory (may be pinned or pageable).
+ device: CUDA device pointer as integer.
+ is_pinned: Whether host memory is pinned (page-locked).
+ Pinned memory provides faster H2D/D2H transfers.
+ host_ptr: Raw pointer for pinned memory (needed for cudaFreeHost).
+ None if using pageable memory.
+
+ Example:
+ >>> mem = HostDeviceMemory(host=np.zeros(100), device=ptr, is_pinned=True)
+ >>> mem.host[:50] = input_data # Copy to host buffer
+ """
+
+ host: np.ndarray
+ device: int
+ is_pinned: bool = False
+ host_ptr: Optional[int] = None
+
+
+# =============================================================================
+# Main Functions
+# =============================================================================
+
+
+def allocate_buffers(
+ engine: trt.ICudaEngine,
+ context: trt.IExecutionContext,
+ use_pinned: bool = True,
+) -> Tuple[List[HostDeviceMemory], List[HostDeviceMemory], List[int], int]:
+ """Allocate host and device buffers for TensorRT inference.
+
+ This function allocates memory buffers for all input and output tensors
+ of a TensorRT engine. It uses the MAXIMUM shape from the optimization
+ profile to ensure buffers are large enough for any valid input shape.
+
+ OPTIMIZATION: Pre-allocating with max shape prevents expensive buffer
+ reallocation during inference. CUDA malloc/free can cost 1-10ms each.
+
+ Args:
+ engine: TensorRT engine containing the optimized network.
+ context: TensorRT execution context for inference.
+ use_pinned: Whether to use pinned (page-locked) memory for host buffers.
+ Pinned memory provides ~2x faster CPU-GPU transfers.
+ Default is True.
+
+ Returns:
+ Tuple containing:
+ - inputs: List of HostDeviceMemory for input tensors
+ - outputs: List of HostDeviceMemory for output tensors
+ - bindings: List of device pointers for TensorRT
+ - stream: CUDA stream handle for async operations
+
+ Raises:
+ AssertionError: If CUDA operations fail.
+
+ Example:
+ >>> inputs, outputs, bindings, stream = allocate_buffers(engine, context)
+ >>> inputs[0].host[:data_size] = input_data
+ """
+ inputs = []
+ outputs = []
+ bindings = []
+
+ # Create CUDA stream (will be reused for all inference calls)
+ status, stream = cudart.cudaStreamCreate()
+ assert status.value == 0, f"Failed to create CUDA stream: {status}"
+
+ for i in range(engine.num_io_tensors):
+ tensor_name = engine.get_tensor_name(i)
+ tensor_mode = engine.get_tensor_mode(tensor_name)
+
+ # Get max shape from optimization profile
+ shape = _get_max_shape(engine, context, tensor_name, tensor_mode)
+
+ # Calculate buffer size
+ size = trt.volume(shape)
+ dtype = trt.nptype(engine.get_tensor_dtype(tensor_name))
+
+ # Allocate host memory (pinned or pageable)
+ host_mem, host_ptr = _allocate_host_memory(size, dtype, use_pinned)
+
+ # Allocate device memory
+ status, device_mem = cudart.cudaMalloc(host_mem.nbytes)
+ assert status.value == 0, (
+ f"Failed to allocate {host_mem.nbytes} bytes of device memory "
+ f"for tensor '{tensor_name}': {status}"
+ )
+
+ # Set tensor address in context
+ context.set_tensor_address(tensor_name, device_mem)
+ bindings.append(device_mem)
+
+ memory = HostDeviceMemory(
+ host=host_mem,
+ device=device_mem,
+ is_pinned=use_pinned and host_ptr is not None,
+ host_ptr=host_ptr,
+ )
+
+ if tensor_mode == trt.TensorIOMode.INPUT:
+ inputs.append(memory)
+ else:
+ outputs.append(memory)
+
+ return inputs, outputs, bindings, stream
+
+
+def free_buffers(
+ inputs: List[HostDeviceMemory],
+ outputs: List[HostDeviceMemory],
+ stream: int = None,
+) -> None:
+ """Free allocated host and device memory buffers.
+
+ This function releases all GPU memory and pinned host memory
+ associated with the given buffers.
+
+ Args:
+ inputs: List of input HostDeviceMemory to free.
+ outputs: List of output HostDeviceMemory to free.
+ stream: CUDA stream (optional, currently unused but kept for API).
+
+ Note:
+ - Device memory is freed with cudaFree
+ - Pinned host memory is freed with cudaFreeHost
+ - Pageable host memory (numpy arrays) is garbage collected automatically
+ """
+ for mem in inputs + outputs:
+ # Free device memory
+ if mem.device != 0:
+ try:
+ cudart.cudaFree(mem.device)
+ except Exception:
+ pass # Ignore cleanup errors
+
+ # Free pinned host memory if applicable
+ if mem.is_pinned and mem.host_ptr is not None:
+ try:
+ cudart.cudaFreeHost(mem.host_ptr)
+ except Exception:
+ pass # Ignore cleanup errors
+
+
+# =============================================================================
+# Private Helper Functions
+# =============================================================================
+
+
+def _get_max_shape(
+ engine: trt.ICudaEngine,
+ context: trt.IExecutionContext,
+ tensor_name: str,
+ tensor_mode: trt.TensorIOMode,
+) -> Tuple[int, ...]:
+ """Get the maximum shape from optimization profile.
+
+ For dynamic shape networks, TensorRT optimization profiles define
+ min/opt/max shapes. This function returns the max shape to ensure
+ allocated buffers can handle any valid input size.
+
+ For INPUT tensors, the max shape is retrieved directly from the profile.
+ For OUTPUT tensors, the max shape is computed by setting all inputs
+ to their max profile shapes and querying the resulting output shape.
+
+ Args:
+ engine: TensorRT engine.
+ context: TensorRT execution context for shape queries.
+ tensor_name: Name of the tensor.
+ tensor_mode: Whether tensor is input or output.
+
+ Returns:
+ Tuple of shape dimensions (max shape from profile or computed).
+ """
+ if tensor_mode == trt.TensorIOMode.INPUT:
+ # For input tensors, get max shape directly from profile
+ try:
+ profile_shape = engine.get_tensor_profile_shape(tensor_name, 0)
+ if profile_shape is not None and len(profile_shape) >= 3:
+ return tuple(profile_shape[2]) # Index 2 = max shape
+ except Exception:
+ pass
+ return DEFAULT_MAX_INPUT_SHAPE
+
+ # For OUTPUT tensors, compute by setting max input shapes and querying output
+ try:
+ # First, set all INPUT tensors to their max profile shapes
+ for i in range(engine.num_io_tensors):
+ name = engine.get_tensor_name(i)
+ mode = engine.get_tensor_mode(name)
+ if mode == trt.TensorIOMode.INPUT:
+ try:
+ profile_shape = engine.get_tensor_profile_shape(name, 0)
+ if profile_shape and len(profile_shape) >= 3:
+ max_input_shape = tuple(profile_shape[2])
+ context.set_input_shape(name, max_input_shape)
+ except Exception:
+ # If we can't get profile, use default
+ context.set_input_shape(name, DEFAULT_MAX_INPUT_SHAPE)
+
+ # Now query the output shape with max inputs set
+ output_shape = context.get_tensor_shape(tensor_name)
+ if output_shape is not None and all(d > 0 for d in output_shape):
+ return tuple(output_shape)
+ except Exception:
+ pass
+
+ # Fallback to default if computation fails
+ return DEFAULT_MAX_OUTPUT_SHAPE
+
+
+def _allocate_host_memory(
+ size: int,
+ dtype: np.dtype,
+ use_pinned: bool,
+) -> Tuple[np.ndarray, Optional[int]]:
+ """Allocate host memory, optionally using pinned (page-locked) memory.
+
+ Pinned memory provides faster CPU-GPU transfers because:
+ - No implicit copy to staging buffer required
+ - Direct DMA transfers are possible
+ - Transfer can be truly asynchronous
+
+ On discrete GPUs (RTX, GTX), pinned memory can be ~2x faster.
+ On Tegra/Jetson with unified memory, the benefit is smaller.
+
+ Args:
+ size: Number of elements to allocate.
+ dtype: NumPy dtype for the array.
+ use_pinned: Whether to attempt pinned memory allocation.
+
+ Returns:
+ Tuple of:
+ - NumPy array (view of pinned memory or regular array)
+ - Raw pointer for cleanup (None if pageable memory)
+ """
+ nbytes = size * np.dtype(dtype).itemsize
+ host_ptr = None
+
+ if use_pinned:
+ try:
+ status, host_ptr = cudart.cudaHostAlloc(nbytes, cudart.cudaHostAllocDefault)
+ if status.value == 0 and host_ptr != 0:
+ # Create numpy array view of pinned memory
+ c_type = _NUMPY_TO_CTYPE.get(np.dtype(dtype).type, ctypes.c_float)
+ ptr_type = ctypes.POINTER(c_type)
+ c_ptr = ctypes.cast(host_ptr, ptr_type)
+ host_mem = np.ctypeslib.as_array(c_ptr, shape=(size,))
+ return host_mem, host_ptr
+ except Exception:
+ pass # Fall through to pageable allocation
+
+ # Reset pointer if pinned allocation failed
+ host_ptr = None
+
+ # Pageable memory fallback
+ host_mem = np.empty(size, dtype=dtype)
+ return host_mem, None
diff --git a/python/rapidocr/utils/typings.py b/python/rapidocr/utils/typings.py
index b0ec1ad..44b941d 100644
--- a/python/rapidocr/utils/typings.py
+++ b/python/rapidocr/utils/typings.py
@@ -53,6 +53,7 @@ class EngineType(Enum):
OPENVINO = "openvino"
PADDLE = "paddle"
TORCH = "torch"
+ TENSORRT = "tensorrt"
MNN = "mnn"
diff --git a/python/tests/test_engine.py b/python/tests/test_engine.py
index 13cff8b..8603b7b 100644
--- a/python/tests/test_engine.py
+++ b/python/tests/test_engine.py
@@ -23,6 +23,7 @@ img_path = tests_dir / "ch_en_num.jpg"
EngineType.OPENVINO,
EngineType.TORCH,
EngineType.MNN,
+ EngineType.TENSORRT,
],
)
def test_ppocrv5_rec_mobile(engine_type):
@@ -48,6 +49,7 @@ def test_ppocrv5_rec_mobile(engine_type):
EngineType.OPENVINO,
EngineType.TORCH,
EngineType.MNN,
+ EngineType.TENSORRT,
],
)
def test_ppocrv5_det_mobile(engine_type):
@@ -111,3 +113,18 @@ def test_engine_torch():
result = engine(img_path)
assert result.txts is not None
assert result.txts[0] == "正品促销"
+
+
+def test_engine_tensorrt():
+ """Test TensorRT engine with full OCR pipeline."""
+ engine = RapidOCR(
+ params={
+ "Det.engine_type": EngineType.TENSORRT,
+ "Cls.engine_type": EngineType.TENSORRT,
+ "Rec.engine_type": EngineType.TENSORRT,
+ }
+ )
+
+ result = engine(img_path)
+ assert result.txts is not None
+ assert len(result.txts) > 0