继续研究如何使用TensorRT
本篇主要阅读TensorRT官方文档
0.简介
本篇主要阅读TensorRT官方文档:TensorRT文档:The C++ API
1.The C++ API
假设从一个 ONNX模型,说明C++API的基本用法。
在sampleOnnxMNIST中可以看到更多的细节。
C++API通过添加头文件及命名空间:
#include “NvInfer.h”
using namespace nvinfer1;
TensorRT C++API中的接口类以前缀I开头,例如ILogger、IBuilder等。
如果先前不存在CUDA上下文context,在TensorRT第一次调用CUDA时会自动创建CUDA上下文。我们通常最好在第一次调用TensorRT之前自己创建和配置CUDA上下文。
为了说明对象的生命周期,本文中代码不使用智能指针;但是,建议将智能指针与TensorRT接口一起使用。
1.1 The Build Phase 构建阶段
To create a builder, you first must instantiate the ILogger interface. This example captures all warning messages but ignores informational messages.
要创建构建器,您首先必须实例化ILogger接口。此示例捕获所有警告消息,但忽略信息性消息:
class Logger : public ILogger
{
void log(Severity severity, const char* msg) noexcept override
{
// suppress info-level messages
if (severity <= Severity::kWARNING)
std::cout << msg << std::endl;
}
} logger;
You can then create an instance of the builder.
然后,可以创建一个实例builder:
IBuilder* builder = createInferBuilder(logger);
1.1.1 Creating a Network Definition 创建网络定义
After the builder has been created, the first step in optimizing a model is to create a network definition. The network creation options are specified using a combination of flags OR-d together.
创建构建器后,优化模型的第一步是创建网络定义。使用标志OR-d的组合来指定网络创建选项。
The kEXPLICIT_BATCH flag is required in order to import models using the ONNX parser. For more information, refer to Explicit Versus Implicit Batch.
需要kEXPLICIT_BATCH标志才能使用ONNX parser方式导入模型,请参阅显式批处理与隐式批处理。
You can also specify that the network should be considered strongly typed using the NetworkDefinitionCreationFlag::kSTRONGLY_TYPED flag. For more information, refer to Strongly Typed Networks.
您还可以使用NetworkDefinitionCreationFlag::kSTRONGLY_TYPED标志,更多信息,请参阅强类型网络。
Finally, create a network
最后,创建一个网络
INetworkDefinition* network = builder->createNetworkV2(flag);
1.1.2 Importing a Model Using the ONNX Parser 使用ONNX解析器导入模型
Now, the network definition must be populated from the ONNX representation. The ONNX parser API is in the file NvOnnxParser.h, and the parser is in the nvonnxparser C++ namespace.
现在,必须从ONNX表示填充网络定义。ONNX解析器API位于文件NvOnnxParser. h中,解析器位于nvonnxparserC++命名空间中。
#include “NvOnnxParser.h”
using namespace nvonnxparser;
You can create an ONNX parser to populate the network as follows
您可以创建一个ONNX解析器来填充网络 如下
IParser* parser = createParser(*network, logger);
Then, read the model file and process any errors.
然后,读取模型文件并处理错误。
parser->parseFromFile(modelFile,
static_cast