Paddle Inference部署推理(十)

十:Paddle Inference推理 (python)API详解

9. 启用内存优化

API定义如下:

# 开启内存 / 显存复用,具体降低内存效果取决于模型结构
# 参数:None
# 返回:None
paddle.inference.Config.enable_memory_optim()

代码示例:

# 引用 paddle inference 预测库
import paddle.inference as paddle_infer

# 创建 config
config = paddle_infer.Config("./mobilenet_v1.pdmodel", "./mobilenet_v1.pdiparams")

# 开启 CPU 显存优化
config.enable_memory_optim()

# 启用 GPU 进行预测
config.enable_use_gpu(100, 0)

# 开启 GPU 显存优化
config.enable_memory_optim()

10. 设置缓存路径

注意: 如果当前使用的为 TensorRT INT8 且设置从内存中加载模型,则必须通过 set_optim_cache_dir 来设置缓存路径。

API定义如下:

# 设置缓存路径
# 参数:opt_cache_dir - 缓存路径
# 返回:None
paddle.inference.Config.set_optim_cache_dir(opt_cache_dir: str)

代码示例:

# 引用 paddle inference 预测库
import paddle.inference as paddle_infer

# 创建 config
config = paddle_infer.Config("./mobilenet_v1.pdmodel", "./mobilenet_v1.pdiparams")

# 设置缓存路径
config.set_optim_cache_dir("./OptimCacheDir")

11. Profile 设置

API定义如下:

# 打开 Profile,运行结束后会打印所有 OP 的耗时占比
# 参数:None
# 返回:None
paddle.inference.Config.enable_profile()

代码示例:

# 引用 paddle inference 预测库
import paddle.inference as paddle_infer

# 创建 config
config = paddle_infer.Config("./mobilenet_v1.pdmodel", "./mobilenet_v1.pdiparams")

# 打开 Profile
config.enable_profile()

执行预测之后输出的 Profile 的结果如下:

------------------------->     Profiling Report     <-------------------------

Place: CPU
Time unit: ms
Sorted by total time in descending order in the same thread

-------------------------     Overhead Summary      -------------------------

Total time: 1085.33
  Computation time       Total: 1066.24     Ratio: 98.2411%
  Framework overhead     Total: 19.0902     Ratio: 1.75893%

-------------------------     GpuMemCpy Summary     -------------------------

GpuMemcpy                Calls: 0           Total: 0           Ratio: 0%

-------------------------       Event Summary       -------------------------

Event                            Calls       Total       Min.        Max.        Ave.        Ratio.
thread0::conv2d                  210         319.734     0.815591    6.51648     1.52254     0.294595
thread0::load                    137         284.596     0.114216    258.715     2.07735     0.26222
thread0::depthwise_conv2d        195         266.241     0.955945    2.47858     1.36534     0.245308
thread0::elementwise_add         210         122.969     0.133106    2.15806     0.585568    0.113301
thread0::relu                    405         56.1807     0.021081    0.585079    0.138718    0.0517635
thread0::batch_norm              195         25.8073     0.044304    0.33896     0.132345    0.0237783
thread0::fc                      15          7.13856     0.451674    0.714895    0.475904    0.0065773
thread0::pool2d                  15          1.48296     0.09054     0.145702    0.0988637   0.00136636
thread0::softmax                 15          0.941837    0.032175    0.460156    0.0627891   0.000867786
thread0::scale                   15          0.240771    0.013394    0.030727    0.0160514   0.000221841

12. Log 设置

API定义如下:

# 去除 Paddle Inference 运行中的 LOG
# 参数:None
# 返回:None
paddle.inference.Config.disable_glog_info()

# 判断是否禁用 LOG
# 参数:None
# 返回:bool - 是否禁用 LOG
paddle.inference.Config.glog_info_disabled()

代码示例:

# 引用 paddle inference 预测库
import paddle.inference as paddle_infer

# 创建 config
config = paddle_infer.Config("./mobilenet_v1.pdmodel", "./mobilenet_v1.pdiparams")

# 去除 Paddle Inference 运行中的 LOG
config.disable_glog_info()

# 判断是否禁用 LOG - true
print("GLOG INFO is: {}".format(config.glog_info_disabled()))

13. 查看config配置

API定义如下:

# 返回 config 的配置信息
# 参数:None
# 返回:string - config 配置信息
paddle.inference.Config.summary()

调用summary()的输出如下所示:

+-------------------------------+----------------------------------+
| Option                        | Value                            |
+-------------------------------+----------------------------------+
| model_dir                     | ./inference_pass/TRTFlattenTest/ |
+-------------------------------+----------------------------------+
| cpu_math_thread               | 1                                |
| enable_mkldnn                 | false                            |
| mkldnn_cache_capacity         | 10                               |
+-------------------------------+----------------------------------+
| use_gpu                       | true                             |
| gpu_device_id                 | 0                                |
| memory_pool_init_size         | 100MB                            |
| thread_local_stream           | false                            |
| use_tensorrt                  | true                             |
| tensorrt_precision_mode       | fp32                             |
| tensorrt_workspace_size       | 1073741824                       |
| tensorrt_max_batch_size       | 32                               |
| tensorrt_min_subgraph_size    | 0                                |
| tensorrt_use_static_engine    | false                            |
| tensorrt_use_calib_mode       | false                            |
| tensorrt_enable_dynamic_shape | false                            |
| tensorrt_use_oss              | true                             |
| tensorrt_use_dla              | false                            |
+-------------------------------+----------------------------------+
| use_xpu                       | false                            |
+-------------------------------+----------------------------------+
| ir_optim                      | true                             |
| ir_debug                      | false                            |
| memory_optim                  | false                            |
| enable_profile                | false                            |
| enable_log                    | true                             |
+-------------------------------+----------------------------------+

<think>嗯,用户的问题是关于如何找到Paddle Inference在CPU上进行推理的C++代码示例。首先,我需要确认PaddlePaddle官方是否有提供相关的文档或示例代码。记得PaddlePaddle的官方文档通常会包含各种部署的示例,包括C++的推理部分。 接下来,用户提到的是CPU上的推理,所以需要确保示例代码是针对CPU环境的,而不是GPU。可能需要检查Paddle Inference的配置选项,比如是否需要在编译时启用或禁用GPU支持。此外,用户可能需要了解如何链接CPU版本的库文件,比如mklml或openblas,这些在CPU推理中可能会用到。 然后,想到用户可能需要具体的步骤,比如如何下载Paddle Inference的C++预测库,如何设置头文件和库路径,以及如何编写CMakeLists.txt。这时候应该分步骤说明,从环境准备到代码示例,再到编译运行,每一步都要详细但清晰。 另外,用户可能遇到的常见问题,比如模型转换。因为Paddle Inference通常需要特定格式的模型,可能需要将训练好的模型转换为Paddle的格式,这里可能需要引用官方提供的模型转换工具,比如paddle2onnx或者直接使用Paddle的保存模型方法。比如引用中的[1]提到了使用paddle2onnx,这可能是一个相关的点,需要提到。 然后,考虑到用户可能需要验证代码的正确性,提供一个简单的示例代码片段会很有帮助。例如,初始化配置、创建预测器、加载模型、准备输入数据、执行推理、获取输出结果这些步骤。代码中需要注意使用命名空间,比如paddle_infer,以及正确的API调用顺序。 另外,可能需要注意不同版本PaddlePaddle的API变化,确保示例代码与用户当前使用的版本兼容。如果用户的环境配置有问题,可能需要提醒他们检查库的路径是否正确,或者是否需要安装额外的依赖项,比如OpenCV或者其他第三方库。 还有,用户提到的参考引用[2]是关于YOLOv5在CPU上的部署,虽然可能不直接相关,但可以推测用户可能在尝试部署视觉模型,因此在示例中可以适当提到图像处理的步骤,比如使用OpenCV读取图像并进行预处理,这样更贴近用户的实际应用场景。 最后,生成的相关问题需要围绕用户可能进一步的需求,比如性能优化、模型转换、多线程处理等,这些都是用户在实现基础推理后可能遇到的进阶问题。</think>以下是关于Paddle Inference在CPU上进行C++推理的代码示例及分步说明: ### 一、环境准备 1. 下载Paddle Inference预测库 前往[PaddlePaddle官网](https://www.paddlepaddle.org.cn/inference/v2.3/user_guides/download_lib.html)下载对应操作系统和编译器版本的C++预测库(选择CPU版本)[^1] 2. 模型准备 使用`paddle.jit.save`保存推理模型,或通过官方工具转换已有模型: ```python import paddle model = paddle.vision.models.ResNet18() paddle.jit.save(model, "inference_model") ``` ### 二、C++代码示例 ```cpp #include <paddle_inference_api.h> #include <iostream> int main() { // 1. 创建配置对象 paddle_infer::Config config; config.SetModel("inference_model.pdmodel", "inference_model.pdiparams"); config.DisableGpu(); // 显式指定CPU推理 // 2. 创建预测器 auto predictor = paddle_infer::CreatePredictor(config); // 3. 准备输入数据 auto input_names = predictor->GetInputNames(); auto input_tensor = predictor->GetInputHandle(input_names[0]); std::vector<int> input_shape = {1, 3, 224, 224}; // 示例输入尺寸 std::vector<float> input_data(1*3*224*224, 1.0); // 填充测试数据 input_tensor->Reshape(input_shape); input_tensor->CopyFromCpu(input_data.data()); // 4. 执行推理 predictor->Run(); // 5. 获取输出 auto output_names = predictor->GetOutputNames(); auto output_tensor = predictor->GetOutputHandle(output_names[0]); std::vector<float> output_data; std::vector<int> output_shape = output_tensor->shape(); int out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1, std::multiplies<int>()); output_data.resize(out_num); output_tensor->CopyToCpu(output_data.data()); std::cout << "Inference completed." << std::endl; return 0; } ``` ### 三、编译配置(CMakeLists.txt示例) ```cmake cmake_minimum_required(VERSION 3.10) project(paddle_demo) # 设置Paddle Inference路径 set(PADDLE_LIB "/path/to/paddle_inference_install_dir") include_directories( ${PADDLE_LIB}/third_party/install/mklml/include ${PADDLE_LIB}/paddle/include ) link_directories( ${PADDLE_LIB}/third_party/install/mklml/lib ${PADDLE_LIB}/paddle/lib ) add_executable(demo main.cpp) target_link_libraries(demo paddle_inference mklml_intel iomp5 pthread dl ) ``` ### 四、运行注意事项 1. 需确保模型路径与代码中指定的路径一致 2. 输入数据需要与模型训练时的预处理保持一致 3. 建议使用OpenCV进行图像预处理(如需要): ```cpp cv::Mat image = cv::imread("test.jpg"); cv::resize(image, image, cv::Size(224, 224)); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值