Deploy AI Model to TensorRT

Parsing and Execution of ONNX Model in C++ with TensorRT

Process to deploy an ONNX model to NVidia's TensorRT computing platform

What is TensorRT?

TensorRT is an execution middleware for Nvidia hardware. TensorRT is as a C++ and Python library. It can be used to optimize and execute ONNX models.

It translates the ONNX model definition into a composition of CUDA kernels through which the data samples flow from the input to the output of the model. The actual composition is optimized for the underlying acceleration hardware.

Nividia TensorRT as a software library to execute ONNX models in C++ and Python

How to Use TensorRT in C++

Execution Steps

To execute in TensorRT, an ONNX model is parsed and optimized. The following steps create an executable TensorRT engine from an ONNX model.

1 ONNX Parsing

ONNX Parser creates a TensorRT network definition from an ONNX model. This network definition contains the model's topology.
The Model Builder optimizes the network: It removes any unused tensors and finds the best mapping of the models components to the GPU resources. The result is a serialized representation of the optimized model to create the TensorRT engine.
The optimization takes time. You can save the store engine. Remember that the model engine is optimized to the specific GPU and will not work on another GPU. #include <string> #include <NvOnnxParser.h> nvinfer1::IHostMemory* parseONNXModel(const std::string& onnxModelPath, Logger& logger) { // create the builder nvinfer1::IBuilder* modelBuilder = nvinfer1::createInferBuilder(logger); // this flag enables dynamic batch sizes (needed for recent versions of ONNX parser) uint32_t networkFlags = 1U <<static_cast<uint32_t> (nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH); // create the network object - this will hold the model's topology nvinfer1::INetworkDefinition* network = modelBuilder->createNetworkV2(networkFlags); // create the ONNX parser nvonnxparser::IParser* onnxParser = nvonnxparser::createParser(*network, logger); // parse the ONNX file const bool didParse = onnxParser->parseFromFile( onnxModelPath.c_str(), (int) nvinfer1::ILogger::Severity::kWARNING ); // check for an error if (!didParse) return nullptr; // create the model builder configuration // this is where you can apply custom configurations nvinfer1::IBuilderConfig *config = modelBuilder->createBuilderConfig(); // optimize the model for local GPU hardware nvinfer1::IHostMemory* serializedModel = modelBuilder->buildSerializedNetwork(*network, *config); // delete all building objects (order matters) delete onnxParser; delete config; delete network; delete modelBuilder; return serializedModel; }

2 Create Model Engine

You can use TensorRT's runtime to create an engine and an execution context.
Think of the engine as the model's executable and the context as the thread which is executing it. It is possible to execute the same engine in multiple contexts in parallel. // create the runtime nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(logger); // the optimized engine nvinfer1::ICudaEngine* engine; // form step 1 nvinfer1::IHostMemory *serializedModel = parseONNXModel( modelPath, serializedModelPath, logger); // check if error if (serializedModel == nullptr) return; // parse the ONNX model from host memory engine = runtime->deserializeCudaEngine(serializedModel->data(), serializedModel->size()); // create the execution context nvinfer1::IExecutionContext* context = engine->createExecutionContext();

3 Engine Execution

After creating the execution context, the engine is ready for execution.
Since the engine is running on the GPU, all inputs and output buffers are allocated in GPU memory. All data needs to be transferred between CPU (host) and GPU (device) memory. // load an example image (this is explained below) float* inputImage; // host memory pointer int inputImageSize; // size of input samples loadImage("image-of-some-aircraft.jpg", &inputImage, &inputImageSize); // the full data size in byte int imageSizeInByte = sizeof(float) * inputImageSize; // allocate the input buffer in GPU memory void* inputBufferGPU; cudaMalloc(&inputBufferGPU, imageSizeInByte); // move the input data to GPU cudaMemcpy(inputBufferGPU, inputImage, imageSizeInByte, cudaMemcpyHostToDevice); // the size of the output buffer is specific to our FGVC model const int numberOfClasses = 70; // 70 aircraft families const int outputBufferSize = sizeof(float) * numberOfClasses; void* outputBufferGPU; // allocate the output buffer cudaMalloc(&outputBufferGPU, outputBufferSize); // an array of pointers to the input/output buffer void* buffers[2]; buffers[0] = inputBufferGPU; buffers[1] = outputBufferGPU; // execute the model engine (by the context) context->executeV2(buffers); // process the model output float maxValue = 0.0f; int index = argMax(outputBufferGPU, numberOfClasses, &maxValue); // print the classification index std::cout << "classification index: " << index << " (at " << maxValue << ")" << std::endl;

Input Image Processing for TensorRT

The input data for a TensorRT engine is always a binary image buffer. Besides the size of the input buffer, there is no validation of the structure or type of buffer data: As long as the buffer size is correct, the engine will execute from any input data. It is your responsibility to ensure that the data presented in the right structure and data type.

While trivial for simple models, the pre-processing of input data for visual models is complex. When we deploy visual models to TensorRT, we spend most our efforts on the programming logic to pre-process imagery.

OpenCV is the usual choice for pre-processing imagery in C++. However, some of its conventions and concepts are different from the visual pre-prosseing of AI training frameworks such as PyTorch. Here is a list of common issues to keep in mind when pre-processing image input data for visual models in TensorRT:

Color Space - BGR and RGB

By default, OpenCV imagery is in BGR color space (Blue Green Red). We find that most models are trained to RGB color space (Red Green Blue). You need to convert the color space before deploying the image data to the buffer. // convert the color space cv::cvtColor(bgrInputImage, rgbOutputImage, cv::COLOR_BGR2RGB);

Data Type - Float 32

While TensorRT supports multiple data types, we find that most visual models are using 32-bit floating point. You need to instruct OpenCV to convert the data of an image to the same type. The OpenCV specifier for 32-bit floating point is CV_32FC3: 32F selects the 32-bit floating point. C3 declares that the three component color space. // convert to floating point 32bit image.convertTo(floatSampleImage, CV_32FC3);

RGB Pixel vs Layer Structure

OpenCV groups the RGB color components per pixel: The buffer starts with the RGB samples of the first pixel before the RGB of the second pixel and so on.
However, essentially all visual AI models separate the RGB color components into separate layers: The input buffer contains all the red samples values before the green and blue samples.
You need to sequence the RGB pixel into layers in OpenCV.

Using OpenCV to structure RGB samples per pixel and per layer

// The descriptor for the output image size // Note that we are creating a 4D image. This will act as a batch input to our model (batch size = 1) // This is the same as calling unsqueeze() in PyTorch. int size[] = {1, 3, rgbPixelImage.rows, rgbPixelImage.cols}; // Allocate the output image with size and depth (ie bits per pixel) cv::Mat rgbLayersImageBatchInput(4, size, rgbPixelImage.depth()); // Vector with mat objects. Each entry is one color layer std::vector<cv::Mat> slices = { cv::Mat(rgbPixelImage.rows, rgbPixelImage.cols, rgbPixelImage.depth(), rgbLayersImageBatchInput.ptr<float>(0, 0)), cv::Mat(rgbPixelImage.rows, rgbPixelImage.cols, rgbPixelImage.depth(), rgbLayersImageBatchInput.ptr<float>(0, 1)), cv::Mat(rgbPixelImage.rows, rgbPixelImage.cols, rgbPixelImage.depth(), rgbLayersImageBatchInput.ptr<float>(0, 2)), }; // Split RGB pixels into layers cv::split(rgbPixelImage, slices); // Three layers of RGB as a buffer pointer float* data = reinterpret_cast<float*>(rgbLayersImageBatchInput.data);