“IRuntime”: 未声明的标识符

举报
风吹稻花香 发表于 2022/07/25 00:18:12 2022/07/25
【摘要】 “IRuntime”: 未声明的标识符 完整用法: TensorRT 系列 (1)模型推理_洪流之源的博客-CSDN博客_tensorrt 推理 // tensorRT include#include <NvInfer.h>#include <NvInferRuntime.h> // cuda incl...

“IRuntime”: 未声明的标识符

完整用法:

TensorRT 系列 (1)模型推理_洪流之源的博客-CSDN博客_tensorrt 推理


  
  1. // tensorRT include
  2. #include <NvInfer.h>
  3. #include <NvInferRuntime.h>
  4. // cuda include
  5. #include <cuda_runtime.h>
  6. // system include
  7. #include <stdio.h>
  8. #include <math.h>
  9. #include <iostream>
  10. #include <fstream>
  11. #include <vector>
  12. using namespace std;
  13. // 上一节的代码
  14. class TRTLogger : public nvinfer1::ILogger
  15. {
  16. public:
  17. virtual void log(Severity severity, nvinfer1::AsciiChar const* msg) noexcept override
  18. {
  19. if(severity <= Severity::kINFO)
  20. {
  21. printf("%d: %s\n", severity, msg);
  22. }
  23. }
  24. } logger;
  25. nvinfer1::Weights make_weights(float* ptr, int n)
  26. {
  27. nvinfer1::Weights w;
  28. w.count = n;
  29. w.type = nvinfer1::DataType::kFLOAT;
  30. w.values = ptr;
  31. return w;
  32. }
  33. bool build_model()
  34. {
  35. TRTLogger logger;
  36. // 这是基本需要的组件
  37. nvinfer1::IBuilder* builder = nvinfer1::createInferBuilder(logger);
  38. nvinfer1::IBuilderConfig* config = builder->createBuilderConfig();
  39. nvinfer1::INetworkDefinition* network = builder->createNetworkV2(1);
  40. // 构建一个模型
  41. /*
  42. Network definition:
  43. image
  44. |
  45. linear (fully connected) input = 3, output = 2, bias = True w=[[1.0, 2.0, 0.5], [0.1, 0.2, 0.5]], b=[0.3, 0.8]
  46. |
  47. sigmoid
  48. |
  49. prob
  50. */
  51. const int num_input = 3;
  52. const int num_output = 2;
  53. float layer1_weight_values[] = {1.0, 2.0, 0.5, 0.1, 0.2, 0.5};
  54. float layer1_bias_values[] = {0.3, 0.8};
  55. nvinfer1::ITensor* input = network->addInput("image", nvinfer1::DataType::kFLOAT, nvinfer1::Dims4(1, num_input, 1, 1));
  56. nvinfer1::Weights layer1_weight = make_weights(layer1_weight_values, 6);
  57. nvinfer1::Weights layer1_bias = make_weights(layer1_bias_values, 2);
  58. auto layer1 = network->addFullyConnected(*input, num_output, layer1_weight, layer1_bias);
  59. auto prob = network->addActivation(*layer1->getOutput(0), nvinfer1::ActivationType::kSIGMOID);
  60. // 将我们需要的prob标记为输出
  61. network->markOutput(*prob->getOutput(0));
  62. printf("Workspace Size = %.2f MB\n", (1 << 28) / 1024.0f / 1024.0f);
  63. config->setMaxWorkspaceSize(1 << 28);
  64. builder->setMaxBatchSize(1);
  65. nvinfer1::ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
  66. if(engine == nullptr)
  67. {
  68. printf("Build engine failed.\n");
  69. return false;
  70. }
  71. // 将模型序列化,并储存为文件
  72. nvinfer1::IHostMemory* model_data = engine->serialize();
  73. FILE* f = fopen("engine.trtmodel", "wb");
  74. fwrite(model_data->data(), 1, model_data->size(), f);
  75. fclose(f);
  76. // 卸载顺序按照构建顺序倒序
  77. model_data->destroy();
  78. engine->destroy();
  79. network->destroy();
  80. config->destroy();
  81. builder->destroy();
  82. printf("Done.\n");
  83. return true;
  84. }
  85. vector<unsigned char> load_file(const string& file)
  86. {
  87. ifstream in(file, ios::in | ios::binary);
  88. if (!in.is_open())
  89. return {};
  90. in.seekg(0, ios::end);
  91. size_t length = in.tellg();
  92. std::vector<uint8_t> data;
  93. if (length > 0){
  94. in.seekg(0, ios::beg);
  95. data.resize(length);
  96. in.read((char*)&data[0], length);
  97. }
  98. in.close();
  99. return data;
  100. }
  101. void inference(){
  102. // ------------------------------ 1. 准备模型并加载 ----------------------------
  103. TRTLogger logger;
  104. auto engine_data = load_file("engine.trtmodel");
  105. // 执行推理前,需要创建一个推理的runtime接口实例。与builer一样,runtime需要logger:
  106. nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(logger);
  107. // 将模型从读取到engine_data中,则可以对其进行反序列化以获得engine
  108. nvinfer1::ICudaEngine* engine = runtime->deserializeCudaEngine(engine_data.data(), engine_data.size());
  109. if(engine == nullptr){
  110. printf("Deserialize cuda engine failed.\n");
  111. runtime->destroy();
  112. return;
  113. }
  114. nvinfer1::IExecutionContext* execution_context = engine->createExecutionContext();
  115. cudaStream_t stream = nullptr;
  116. // 创建CUDA流,以确定这个batch的推理是独立的
  117. cudaStreamCreate(&stream);
  118. /*
  119. Network definition:
  120. image
  121. |
  122. linear (fully connected) input = 3, output = 2, bias = True w=[[1.0, 2.0, 0.5], [0.1, 0.2, 0.5]], b=[0.3, 0.8]
  123. |
  124. sigmoid
  125. |
  126. prob
  127. */
  128. // ------------------------------ 2. 准备好要推理的数据并搬运到GPU ----------------------------
  129. float input_data_host[] = {1, 2, 3};
  130. float* input_data_device = nullptr;
  131. float output_data_host[2];
  132. float* output_data_device = nullptr;
  133. cudaMalloc(&input_data_device, sizeof(input_data_host));
  134. cudaMalloc(&output_data_device, sizeof(output_data_host));
  135. cudaMemcpyAsync(input_data_device, input_data_host, sizeof(input_data_host), cudaMemcpyHostToDevice, stream);
  136. // 用一个指针数组指定input和output在gpu中的指针。
  137. float* bindings[] = {input_data_device, output_data_device};
  138. // ------------------------------ 3. 推理并将结果搬运回CPU ----------------------------
  139. bool success = execution_context->enqueueV2((void**)bindings, stream, nullptr);
  140. cudaMemcpyAsync(output_data_host, output_data_device, sizeof(output_data_host), cudaMemcpyDeviceToHost, stream);
  141. cudaStreamSynchronize(stream);
  142. printf("output_data_host = %f, %f\n", output_data_host[0], output_data_host[1]);
  143. // ------------------------------ 4. 释放内存 ----------------------------
  144. printf("Clean memory\n");
  145. cudaStreamDestroy(stream);
  146. execution_context->destroy();
  147. engine->destroy();
  148. runtime->destroy();
  149. // ------------------------------ 5. 手动推理进行验证 ----------------------------
  150. const int num_input = 3;
  151. const int num_output = 2;
  152. float layer1_weight_values[] = {1.0, 2.0, 0.5, 0.1, 0.2, 0.5};
  153. float layer1_bias_values[] = {0.3, 0.8};
  154. printf("手动验证计算结果:\n");
  155. for(int io = 0; io < num_output; ++io)
  156. {
  157. float output_host = layer1_bias_values[io];
  158. for(int ii = 0; ii < num_input; ++ii)
  159. {
  160. output_host += layer1_weight_values[io * num_input + ii] * input_data_host[ii];
  161. }
  162. // sigmoid
  163. float prob = 1 / (1 + exp(-output_host));
  164. printf("output_prob[%d] = %f\n", io, prob);
  165. }
  166. }
  167. int main()
  168. {
  169. if(!build_model())
  170. {
  171. return -1;
  172. }
  173. inference();
  174. return 0;
  175. }

原文链接:https://blog.csdn.net/weicao1990/article/details/125034572

makefile:


  
  1. cc := g++
  2. name := pro
  3. workdir := workspace
  4. srcdir := src
  5. objdir := objs
  6. stdcpp := c++11
  7. cuda_home := /home/liuhongyuan/miniconda3/envs/trtpy/lib/python3.8/site-packages/trtpy/trt8cuda112cudnn8
  8. syslib := /home/liuhongyuan/miniconda3/envs/trtpy/lib/python3.8/site-packages/trtpy/lib
  9. cpp_pkg := /home/liuhongyuan/miniconda3/envs/trtpy/lib/python3.8/site-packages/trtpy/cpp-packages
  10. cuda_arch :=
  11. nvcc := $(cuda_home)/bin/nvcc -ccbin=$(cc)
  12. # 定义cpp的路径查找和依赖项mk文件
  13. cpp_srcs := $(shell find $(srcdir) -name "*.cpp")
  14. cpp_objs := $(cpp_srcs:.cpp=.cpp.o)
  15. cpp_objs := $(cpp_objs:$(srcdir)/%=$(objdir)/%)
  16. cpp_mk := $(cpp_objs:.cpp.o=.cpp.mk)
  17. # 定义cu文件的路径查找和依赖项mk文件
  18. cu_srcs := $(shell find $(srcdir) -name "*.cu")
  19. cu_objs := $(cu_srcs:.cu=.cu.o)
  20. cu_objs := $(cu_objs:$(srcdir)/%=$(objdir)/%)
  21. cu_mk := $(cu_objs:.cu.o=.cu.mk)
  22. # 定义opencv和cuda需要用到的库文件
  23. link_cuda := cudart cudnn
  24. link_trtpro :=
  25. link_tensorRT := nvinfer
  26. link_opencv :=
  27. link_sys := stdc++ dl
  28. link_librarys := $(link_cuda) $(link_tensorRT) $(link_sys) $(link_opencv)
  29. # 定义头文件路径,请注意斜杠后边不能有空格
  30. # 只需要写路径,不需要写-I
  31. include_paths := src \
  32. $(cuda_home)/include/cuda \
  33. $(cuda_home)/include/tensorRT \
  34. $(cpp_pkg)/opencv4.2/include
  35. # 定义库文件路径,只需要写路径,不需要写-L
  36. library_paths := $(cuda_home)/lib64 $(syslib) $(cpp_pkg)/opencv4.2/lib
  37. # 把library path给拼接为一个字符串,例如a b c => a:b:c
  38. # 然后使得LD_LIBRARY_PATH=a:b:c
  39. empty :=
  40. library_path_export := $(subst $(empty) $(empty),:,$(library_paths))
  41. # 把库路径和头文件路径拼接起来成一个,批量自动加-I、-L、-l
  42. run_paths := $(foreach item,$(library_paths),-Wl,-rpath=$(item))
  43. include_paths := $(foreach item,$(include_paths),-I$(item))
  44. library_paths := $(foreach item,$(library_paths),-L$(item))
  45. link_librarys := $(foreach item,$(link_librarys),-l$(item))
  46. # 如果是其他显卡,请修改-gencode=arch=compute_75,code=sm_75为对应显卡的能力
  47. # 显卡对应的号码参考这里:https://developer.nvidia.com/zh-cn/cuda-gpus#compute
  48. # 如果是 jetson nano,提示找不到-m64指令,请删掉 -m64选项。不影响结果
  49. cpp_compile_flags := -std=$(stdcpp) -w -g -O0 -m64 -fPIC -fopenmp -pthread
  50. cu_compile_flags := -std=$(stdcpp) -w -g -O0 -m64 $(cuda_arch) -Xcompiler "$(cpp_compile_flags)"
  51. link_flags := -pthread -fopenmp -Wl,-rpath='$$ORIGIN'
  52. cpp_compile_flags += $(include_paths)
  53. cu_compile_flags += $(include_paths)
  54. link_flags += $(library_paths) $(link_librarys) $(run_paths)
  55. # 如果头文件修改了,这里的指令可以让他自动编译依赖的cpp或者cu文件
  56. ifneq ($(MAKECMDGOALS), clean)
  57. -include $(cpp_mk) $(cu_mk)
  58. endif
  59. $(name) : $(workdir)/$(name)
  60. all : $(name)
  61. run : $(name)
  62. @cd $(workdir) && ./$(name) $(run_args)
  63. $(workdir)/$(name) : $(cpp_objs) $(cu_objs)
  64. @echo Link $@
  65. @mkdir -p $(dir $@)
  66. @$(cc) $^ -o $@ $(link_flags)
  67. $(objdir)/%.cpp.o : $(srcdir)/%.cpp
  68. @echo Compile CXX $<
  69. @mkdir -p $(dir $@)
  70. @$(cc) -c $< -o $@ $(cpp_compile_flags)
  71. $(objdir)/%.cu.o : $(srcdir)/%.cu
  72. @echo Compile CUDA $<
  73. @mkdir -p $(dir $@)
  74. @$(nvcc) -c $< -o $@ $(cu_compile_flags)
  75. # 编译cpp依赖项,生成mk文件
  76. $(objdir)/%.cpp.mk : $(srcdir)/%.cpp
  77. @echo Compile depends C++ $<
  78. @mkdir -p $(dir $@)
  79. @$(cc) -M $< -MF $@ -MT $(@:.cpp.mk=.cpp.o) $(cpp_compile_flags)
  80. # 编译cu文件的依赖项,生成cumk文件
  81. $(objdir)/%.cu.mk : $(srcdir)/%.cu
  82. @echo Compile depends CUDA $<
  83. @mkdir -p $(dir $@)
  84. @$(nvcc) -M $< -MF $@ -MT $(@:.cu.mk=.cu.o) $(cu_compile_flags)
  85. # 定义清理指令
  86. clean :
  87. @rm -rf $(objdir) $(workdir)/$(name) $(workdir)/*.trtmodel
  88. # 防止符号被当做文件
  89. .PHONY : clean run $(name)
  90. # 导出依赖库路径,使得能够运行起来
  91. export LD_LIBRARY_PATH:=$(library_path_export)

原文链接:https://blog.csdn.net/weicao1990/article/details/125034572

重点提炼:
1. 必须使用createNetworkV2,并指定为1(表示显性batch),createNetwork已经废弃,非显性batch官方不推荐,这个方式直接影响推理时enqueue还是enqueueV2;

2. builder、config等指针,记得释放,否则会有内存泄漏,使用ptr->destroy()释放;

3. markOutput表示是该模型的输出节点,mark几次,就有几个输出,addInput几次就有几个输入;

4. workspaceSize是工作空间大小,某些layer需要使用额外存储时,不会自己分配空间,而是为了内存复用,直接找tensorRT要workspace空间;

5. 一定要记住,保存的模型只能适配编译时的trt版本、编译时指定的设备,也只能保证在这种配置下是最优的。如果用trt跨不同设备执行,有时候可以运行,但不是最优的,也不推荐;

6. bindings是tensorRT对输入输出张量的描述,bindings = input-tensor + output-tensor。比如input有a,output有b, c, d,那么bindings = [a, b, c, d],bindings[0] = a,bindings[2] = c;

7. enqueueV2是异步推理,加入到stream队列等待执行。输入的bindings则是tensors的指针(注意是device pointer);

8. createExecutionContext可以执行多次,允许一个引擎具有多个执行上下文。
————————————————
版权声明:本文为CSDN博主「洪流之源」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weicao1990/article/details/125034572

文章来源: blog.csdn.net,作者:AI视觉网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/125962123

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200